UserDetails的自定义实现示例

时间:2011-10-12 09:01:43

标签: spring spring-security

我正在寻找在Spring Security 3中创建自定义UserDetails对象的示例。 而且我希望有人可以提供帮助,谢谢。

1 个答案:

答案 0 :(得分:8)

这是我用过的东西:

public class CustomUserDetails implements UserDetails {
    private  User user;

    public CustomUserDetails(final User _user) {
            this.user = _user;
    }

    public CustomUserDetails() {
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
             final Set<GrantedAuthority> _grntdAuths = new HashSet<GrantedAuthority>();

     List<UserRole> _roles = null;

     if (user!=null) {
             _roles = user.getRoles();
     }

     if (_roles!=null) {
             for (UserRole _role : _roles) {
                     _grntdAuths.add(new GrantedAuthorityImpl(_role.getRole()));
             }
     }

     return _grntdAuths;
    }

    @Override
    public String getPassword() {
            return user.getPassword();
    }
 @Override
    public String getUsername() {
            if (this.user == null) {
                    return null;
            }
            return this.user.getUser_name();
    }

    @Override
    public boolean isAccountNonExpired() {
            return this.user.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
            return this.user.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
            return this.user.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
            return this.user.isEnabled();
    }

    public User getUser() {
            return user;
    }

    @Override
    public String toString() {
            return "CustomUserDetails [user=" + user + "]";
    }
}