Spring Security 3 Active Directory Authentication,

2019-01-12 04:49发布

I'm trying to acces my application with AD authentication and getting authorization roles from my DB.

this is my configuration

<beans:bean id="activeDirectoryAuthenticationProvider"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <beans:constructor-arg value="mydomain" />
    <beans:constructor-arg value="ldap://my URL :389" />
    <beans:property name="convertSubErrorCodesToExceptions" value="true"/>
</beans:bean>

I tried to add

  <beans:constructor-arg>
    <beans:bean class="org.springframework.security.ldap.populator.UserDetailsServiceLdapAuthoritiesPopulator">
      <beans:constructor-arg ref="myUserDetailsService"/>
    </beans:bean>
  </beans:constructor-arg>

but it didn't work. Any help?

Many thanks!!

3条回答
趁早两清
2楼-- · 2019-01-12 05:12

ActiveDirectoryLdapAuthenticationProvider doesn't use an LdapAuthoritiesPopulator (check the API for the constructor).

You can use a delegation model, where you wrap the provider and load the authorities separately, before returning a new token containing them:

public class MyAuthoritySupplementingProvider implements AuthenticationProvider {
    private AuthenticationProvider delegate;

    public MyAuthoritySupplementingProvider(AuthenticationProvider delegate) {
        this.delegate = delegate;
    }

    public Authentication authenticate(Authentication authentication) {
        final Authentication a = delegate.authenticate(authentication);

        // Load additional authorities and create an Authentication object
        final List<GrantedAuthority> authorities = loadRolesFromDatabaseHere(a.getName());

        return new AbstractAuthenticationToken(authorities) {
            public Object getCredentials() {
                throw new UnsupportedOperationException();
            }

            public Object getPrincipal() {
                return a.getPrincipal();
            }
        };
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return delegate.supports(authentication);
    }
}

The class is final mainly due to my rather basic knowledge of Active Directory and the different ways people would want to use it.

查看更多
乱世女痞
3楼-- · 2019-01-12 05:17

Need to set authenticated flag as true in AbstractAuthenticationToken, unless its not take it as success

查看更多
三岁会撩人
4楼-- · 2019-01-12 05:34

Lets break this up into 2 parts. First one would be your spring security xml configuration and the second part would be overriding the UserContextMapper that spring security provides.

Your security xml configuration would be

<bean id="adAuthenticationProvider"
    class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
   <constructor-arg value="my.domain.com" />
    <constructor-arg value="ldap://<adhostserver>:<port>/" />
    <property name="convertSubErrorCodesToExceptions" value="true" />
    <property name="userDetailsContextMapper" ref="myUserDetailsContextMapper" />
</bean>

<bean id="myUserDetailsContextMapper" class="com.mycompany.sme.workflow.controller.MyDbAuthorizationFetcher">
<property name="dataSource" ref="dataSource" />

The MyDbAuthorizationFetcher is the class where you would be implementing UserContextMapper class to fetch authorities from DB

public class MyDbAuthorizationFetcher implements UserDetailsContextMapper {

private JdbcTemplate jdbcTemplate;
@Autowired
private DataSource dataSource;

public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

public DataSource getDataSource() {
    return dataSource;
}

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

// populating roles assigned to the user from AUTHORITIES table in DB
private List<SimpleGrantedAuthority> loadRolesFromDatabase(String username) {

    DbRole role = new DbRole();
    String sql = "select * from user where user_id = ?";
    jdbcTemplate = new JdbcTemplate(getDataSource());
    role = jdbcTemplate.queryForObject(sql, new Object[] { username }, new DbRoleMapper());


    try {
        dataSource.getConnection().setAutoCommit(true);
    } catch (SQLException e) {

    }
    List<SimpleGrantedAuthority> authoritiess = new ArrayList<SimpleGrantedAuthority>();
    SimpleGrantedAuthority auth = new SimpleGrantedAuthority(String.valueOf(role.getRoleId()));
    authoritiess.add(auth);
    return authoritiess;

   }

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx,
        String username, Collection<? extends GrantedAuthority> authorities) {

    List<SimpleGrantedAuthority> allAuthorities = new ArrayList<SimpleGrantedAuthority>();
      for (GrantedAuthority auth : authorities) {
        if (auth != null && !auth.getAuthority().isEmpty()) {
           allAuthorities.add((SimpleGrantedAuthority) auth);
        }
      }
      // add additional roles from the database table
      allAuthorities.addAll(loadRolesFromDatabase(username));
      return new User(username, "", true, true, true, true, allAuthorities);
}

@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
    // TODO Auto-generated method stub
}

}
查看更多
登录 后发表回答