本文介绍了UserDetails 的自定义实现示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在 Spring Security 3 中创建自定义 UserDetails 对象的示例.我希望有人能帮忙,谢谢.

I am looking for an example of making a custom UserDetails object in Spring Security 3.And I was hoping if anyone can help, thanks.

推荐答案

这是我用过的:

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 + "]";
    }
}

这篇关于UserDetails 的自定义实现示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 18:15