如何连接Ldap服务器以及如何在Spring Bott Apllication中验证AD组

时间:2017-12-15 05:39:44

标签: spring spring-boot ldap

我有一个春季启动应用程序。我想连接ldap服务器,并希望查询验证ldap服务器具有的AD组。请有人建议我这方面的工作。

1 个答案:

答案 0 :(得分:0)

我希望您熟悉Spring Security。编写一个扩展WebSecurityConfigurerAdapter并配置AD身份验证提供程序的配置类。请参阅以下代码。更改antMatchers以匹配您的应用。 添加依赖项spring-security-ldap,spring-boot-starter-security。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
    private Environment env;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers(AppConstants.LOGIN_URI).fullyAuthenticated().and().formLogin().permitAll();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        String ldapUrl = env.getProperty(AppConstants.LDAP_URL);
        String ldapDomain = env.getProperty(AppConstants.LDAP_DOMAIN);
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(ldapDomain,
                ldapUrl);
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        auth.authenticationProvider(provider);
    }

要获取为其分配用户的组,请在控制器类中注入Authentication / Principal实例。得到 要获得针对用户的所有属性,如电子邮件,经理等,您可能需要编写自定义映射器。请参阅下面的代码。

@GetMapping(value = { AppConstants.REST_API_LOGIN })
    public ResponseEntity<User> authenticateUser(Authentication auth) {
        List<String> ldapRoles = new ArrayList<String>();
        auth.getAuthorities().forEach(a -> ldapRoles.add(a.getAuthority()));
/*
Write service class methods to compare ldapRoles against app specific roles from DB and exception handlers to handle exceptions
*/
    User user = userService.getUser(auth);
    if (!user.isAuthorized()) {
        logger.info("User:" + auth.getName() + " is not authorized to access program.");
        throw new UserAuthenticationException(AppConstants.NOT_VALID_MEMBER, user);
    }
    logger.info("User:" + auth.getName() + " logged in");
    return new ResponseEntity<User>(user, HttpStatus.OK);
}