在SpringBoot中集成AD认证,有两种模式直接认证模式和Bind模式。
直接认证模式,只需要配置AD的URL即可,无需引入额外的依赖包。
@PostMapping("/login")
public AjaxResult<Object> login(@RequestBody UserVO user) {
try {
Hashtable<String, String> hashEnv = new Hashtable<>();
hashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
hashEnv.put(Context.PROVIDER_URL, Util.getProperty("ad.url", "ldap://www.abc.com:389"));
hashEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
hashEnv.put(Context.REFERRAL, "follow");
hashEnv.put(Context.SECURITY_PRINCIPAL, user.getUsername());
hashEnv.put(Context.SECURITY_CREDENTIALS, user.getPassword());
hashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");
hashEnv.put("java.naming.ldap.attributes.binary", "objectSid");
DirContext ctx = new InitialDirContext(hashEnv);
ctx.close();
log.debug("AD Login success");
return AjaxResult.ok(null, "Login Success");
} catch (AuthenticationException e) {
String s = "AD authorization failed: " + e.getMessage();
log.error(s);
return AjaxResult.fail(s);
} catch (CommunicationException e) {
String s = "AD connection failed: " + e.getMessage();
log.error(s);
return AjaxResult.fail(s);
} catch (Exception e) {
String s = "unknown error: " + e.getMessage();
log.error(s);
return AjaxResult.fail(s);
}
}
{
"username": "username",
"password": "password"
}
Bind模式,通过 LdapTemplate 组件来进行验证。需要引入额外的依赖。Bind模式用户名无需添加域后缀,因为配置中已经指定了base。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
spring.ldap.urls=ldap://www.abc.com:389
spring.ldap.base=DC=abc,DC=com
spring.ldap.username=bind_username@abc.com
spring.ldap.password=bind_user_password
@Autowired
private LdapTemplate ldapTemplate;
@PostMapping("/login")
public AjaxResult<Object> login(@RequestBody UserVO user) {
try {
DirContext ctx = ldapTemplate.getContextSource().getContext(user.getUsername(), user.getPassword());
EqualsFilter filter = new EqualsFilter("sAMAccountName", user.getUsername());
ldapTemplate.setIgnorePartialResultException(true);
boolean flag = ldapTemplate.authenticate("", filter.toString(), user.getPassword());
if (flag) {
return AjaxResult.ok(true, "login success");
} else {
return AjaxResult.fail("login failed");
}
} catch (Exception e) {
return AjaxResult.fail(e.getMessage());
}
}
{
"username": "username",
"password": "password"
}