问题
In my non Spring Security application, we used LDAP to authenticate users by connecting to the LDAP server using his ID and password. If the connection was successful, then the user was authenticated and his details were gotten from LDAP. Below is the code for that:
private void getLdapConnection(UserSignInObject userSignInObject) {
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://mjkoldc-03.red.com");
ctxSrc.setUserDn("mj\\" + userSignInObject.getEmail());
ctxSrc.setPassword(userSignInObject.getPassword());
ctxSrc.setReferral("follow");
ctxSrc.afterPropertiesSet();
LdapTemplate tmpl = new LdapTemplate(ctxSrc);
setLdapTemplate(tmpl);
}
@Override
public DefaultUserObject selectUserDetailsFromLdap(
UserSignInObject userSignInObject) throws Exception {
DefaultUserObject user = new DefaultUserObject();
try {
getLdapConnection(userSignInObject);
LdapQuery query = query().base("dc=metaljunction,dc=com")
.attributes("GivenName", "sn", "mail", "MobilePhone")
.where("ObjectClass").is("user").and("SamAccountName")
.is(userSignInObject.getEmail());
user = ldapTemplate.searchForObject(query,
new ContextMapper<DefaultUserObject>() {
@Override
public DefaultUserObject mapFromContext(Object ctx)
throws NamingException {
DirContextAdapter context = (DirContextAdapter) ctx;
DefaultUserObject user = new DefaultUserObject();
user.setFirstName(context
.getStringAttribute("GivenName"));
user.setLastName(context.getStringAttribute("sn"));
user.setEmail(context.getStringAttribute("mail"));
user.setPhone(context
.getStringAttribute("MobilePhone"));
return user;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
The requirement is to implement the same logic in Spring Security 4. I want to save the details in the Authentication
and UserDetails
objects. How do I do it? I am using Java based config. This is the only way to authenticate the user.
回答1:
You need to implement your own AuthenticationProvider (i.e. a class implementing org.springframework.security.authentication.AuthenticationProvider) and configure Spring Security to use it. Give a look to this: Implement custom AuthenticationProvider in Spring Security 2.06
来源:https://stackoverflow.com/questions/28554949/custom-ldap-authentication-using-spring-security-4