I have tried to implement a success handler for login using Spring security with LDAP in my web app. After searching online, the only way I found was to implement a custom user details mapper like so:
public class CustomUserDetailsMapper extends LdapUserDetailsMapper{
private static final String ROLE_NORMAL_USER = "Normal User";
private static final String ROLE_ADMIN = "Administrator";
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx,
String username, Collection<? extends GrantedAuthority> authority) {
UserDetails originalUser = super.mapUserFromContext( ctx, username, authority );
originalUser.getAuthorities();
Set<AndaAuthority> roles = EnumSet.noneOf(AndaAuthority.class);
roles.add(AndaAuthority.ROLE_ADMIN);
for (GrantedAuthority auth : authority) {
if (ROLE_NORMAL_USER.equalsIgnoreCase(auth.getAuthority())) {
roles.add(AndaAuthority.ROLE_USER);
} else if (ROLE_ADMIN.equalsIgnoreCase(auth.getAuthority())) {
roles.add(AndaAuthority.ROLE_ADMIN);
}
}
SecurityContextHolder.getContext().getAuthentication().getCredentials();
User newUser =
new User(
originalUser.getUsername(),
originalUser.getPassword() != null? originalUser.getPassword():"",
originalUser.isEnabled(),
originalUser.isAccountNonExpired(),
originalUser.isCredentialsNonExpired(),
originalUser.isAccountNonLocked(),
roles );
return newUser;
}
}
This was working - when I put a breakpoint here it stopped. But, is there a better way to implement a handler for such a case? I mean, the whole authentication part is done "under the hood" and I cannot really debug if something goes wrong and this method is not called, I have no other way to know where something went wrong on the way.
Thank you
For anyone else wondering: You must declare your success handler as a bean so you can link it in your Spring security configuration.
The implementation from here works well, you only have to declare your authentication-success-handler-ref
in your <form-login>
configuration tag and override the onAuthenticationSuccess
method.
Other better solutions may exist, but this is the one that I found and worked in my case.
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.