简体   繁体   English

Spring Security LDAP成功处理程序

[英]Spring security LDAP success handler

I have tried to implement a success handler for login using Spring security with LDAP in my web app. 我已经尝试在我的Web应用程序中使用带有LDAP的Spring安全性实现用于登录的成功处理程序。 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. 对于其他任何想知道的人:您必须将成功处理程序声明为Bean,以便可以在Spring安全配置中将其链接。

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. 此处的实现效果很好,您只需在<form-login>配置标记中声明您的authentication-success-handler-ref并覆盖onAuthenticationSuccess方法。

Other better solutions may exist, but this is the one that I found and worked in my case. 可能存在其他更好的解决方案,但这是我在我的案例中找到并使用的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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