Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of custom implementation of 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.

like image 443
Mahmoud Saleh Avatar asked Oct 24 '25 19:10

Mahmoud Saleh


1 Answers

Here's what I've used:

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 + "]";
    }
}
like image 75
gouki Avatar answered Oct 26 '25 09:10

gouki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!