简体   繁体   中英

Spring Security 3 Active Directory Authentication, Database Authorization

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!!

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.

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
}

}

需要在AbstractAuthenticationToken中将authenticated标志设置为true,除非未将其视为成功

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM