Announcement Announcement Module
Collapse
No announcement yet.
How to use custom userDetails in Spring Security Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to use custom userDetails in Spring Security

    Hi,

    I am authentication using custom UserDetailsService and its working fine. My question is, in

    publice UserDetails loadUserByUsername

    function I am returning org.springframework.security.core.userdetails.User . Now I want to have my custom class that will implement UserDetails Interface and I want to return Instance of that class from function loadUserByUsername.

    Reason for this is I want to add extra information in the spring security session. And this is the only possible solution I could think of.

    Please tell me how can I do it. Or if there is anything else that i should do to add extra information to session like userId

  • #2
    After hours of searching and experimenting I was able to do it like this.

    Make a new service say MyUserService that will implement org.springframework.security.core.userdetails.User DetailsService and has annotation @Service. UserDetailsService only has one method loadUserByUserName. Implementation of this method will be in MyUserService. It will look like this.

    @Service public class MyUserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String arg0)
    throws UsernameNotFoundException {

    MyUser user=new MyUser();
    /*get details of user and authorities from database whose username is
    arg0 and place them in user instance */
    return user;
    }

    }
    MyUser is also a new class that implements org.springframework.security.core.userdetails.User Details and all its methods are implemented inside MyUser class. It will look like this.

    public class MyUser implements UserDetails {
    private static final long serialVersionUID = 1L;
    /*All the variables their getter setters that you wish to store in session. And
    implementation of all the methods of UserDetails go here.*/

    }
    Define a bean like this <bean id="customUserDetailsService" class="org.aurora.timeexpense.service.MyUserServic e"/>
    Where org.aurora.timeexpense.service.MyUserService is the path of my defined service that implements UserDetailsService.

    4.And Spring Security Configuration will go like this <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="customUserDetailsService"> </authentication-provider> </authentication-manager>

    You are good to go.

    Comment

    Working...
    X