Spring access to UserDetailsService security from deeper layers


I have the following implementation of UserDetailsService.
So far, the authentication process has worked great.
How to save my "MyOser bean" ( which was successfully registered ) in a "session" so that I can access it in other areas of my application.

Thank.

@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {


    private EmployeesApi employeesApi = new EmployeesApi();

    /**
     * Retrieves a user record containing the user credentials and access. 
     */
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException, DataAccessException {

        // Declare a null Spring User
        UserDetails user = null;

        try {


            MyUser employee = employeesApi.getByUserName(userName);



            user =  new User(
                    employee.getUserName(), 
                    employee.getPassword().toLowerCase(),
                    true,
                    true,
                    true,
                    true,
                    getAuthorities(1) );

        } catch (Exception e) {
            logger.error("Error in retrieving user");
            throw new UsernameNotFoundException("Error in retrieving user");
        }


    }
    ....
+3
source share
1 answer

Spring Security already stores the UserDetailsauthenticated user in a session for you.

So, the easiest way to save MyUserin a session is to implement a custom UserDetailsone containing a link to MyUser:

public class MyUserDetails extends User {
    private MyUser myUser;
    public MyUserDetails(..., MyUser myUser) {
        super(...);
        this.myUser = myUser;
    }
    public MyUser getMyUser() {
        return myUser;
    }
    ...
}

UserDetailsService:

MyUser employee = employeesApi.getByUserName(userName);
user =  new MyUserDetails(..., myUser);

MyUser :

MyUser myUser = ((MyUserDetails) SecurityContextHolder
    .getContext().getAuthentication().getPrincipal()).getMyUser();

Spring MVC-:

@RequestMapping(...)
public ModelAndView someController(..., Authentication auth) {
    MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser();
    ...
}

JSP:

<security:authentication var = "myUser" property="principal.myUser" />
+6

Source: https://habr.com/ru/post/1790288/


All Articles