Sergei Sergei - 2 months ago 17
Java Question

Spring get custom UserDetails in SecurityContextHolder

I use SpringSecurity in my web-project. I have entity User that saved in DB. I need to do requests in BD with user's id to get any inormation from others tables in this BD. How can I get my user from SecurityContextHolder instead standart Spring User( this user haven't id) after authentiication in Spring Security ?

@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "name")
private String name;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

+ getters and setters


PS.Sorry for my english :)

Answer

You would implement the UserDetailsService interface and the UserDetails interface in another class. For example:

CustomUserDetailsService:

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    // your UserRepository for your user
    private final UserRepository userRepository;

    @Autowired
    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (null == user || ! user.getUsername().equals(username)) {
            throw new UsernameNotFoundException("No user present with username: " + username);
        } else {

            return new CustomUserDetails(user);
        }
    }
}

CustomUserDetails:

// You want to extend your User class here
public class CustomUserDetails extends User implements UserDetails {
    private static final long serialVersionUID = 1L;
    private Users user;

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

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // You don't talk about UserRoles, so return ADMIN for everybody or implement roles. 
        return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        // just for example
        return this.user.getActive() == true;
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    // Just an example to put some addititional Data to your logged in user

    public String getUserDatabase() {
        return "usertable" + Integer.toString(1 + this.user.getUserId());
    }


}

In your User class, create an empty constructor for hibernate, and one that takes a User instance:

@Entity
@Table(name = "users")
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    public User() {}

    public User(User user) {
        this.id = user.getId();
        this.name = user.getName();
        // … the same for all properties.
    }
}

In your WebSecurityConfig, @Autowire the CustomUserDetailsService and inject it in the auth flow:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final
    UserDetailsService service;

    @Autowired
    public WebSecurityConfig(UserDetailsService service) {
        this.service = service;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(service).passwordEncoder(passwordEncoder());

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //left out because not related here
    }
}

And that's it. You can now cast the authenticated principal to you CustomUserDetails in every controller or in a provider with:

CustomUserDetails userDetails = 
    (CustomUserDetails) SecurityContextHolder
        .getContext()
        .getAuthentication()
        .getPrincipal();