Home > Software design >  Spring Security access any user Authentication object
Spring Security access any user Authentication object

Time:09-26

I'm working on the SpringBoot stateful application. For the administration purpose, I need to be able to access any user session and modify the attributes there.

Right now, I know how to successfully access the current (my) user Authentication object:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2User principal = (OAuth2User) authentication.getPrincipal();

but how to do the same for any other user?

Is it possible to find the session by username or something similar? I'd really appreciate the example.

CodePudding user response:

There is no built-in mechanism to do something like what you want, but you can write a custom HttpSessionListener that would save references to active sessions, remove them upon expiration and also expose some methods to manipulate session attributes. You would also probably want to associate some user id with the sessions that you can use to perform user lookup, so registering an AuthenticationSuccessHandler to do that would also be needed.

Your logged in users' manager would look something like this:

@Service
public class LoggedInUsersManagerService implements HttpSessionListener {

    // assuming you have some session storage here, 
    // can be something as simple as just a map

    public void sessionCreated(HttpSessionEvent se) {
        final HttpSession session = se.getSession();
        sessionStore.put(session.getAttribute(USER_ID_ATTRIBUTE), session);
    }


    public void sessionDestroyed(HttpSessionEvent se) {
        final HttpSession session = se.getSession();
        sessionStore.remove(session.getAttribute(USER_ID_ATTRIBUTE));
    }

    public void doSomethingWithUserSession(UserIdType id) {
        final HttpSession session = sessionStore.get(id);
        if(session != null) {
            //do what you need with the session attributes
        }
    }
}

and your SuccessHandler would look like

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession();
        session.setAttribute(USER_ID_ATTRIBUTE, getUserIdFromAUthentication(authentication));
        //maybe do something else as well
    }

}

You can register the success handler in your spring security configuration, for example like this

http
    .oauth2login()
    .successHandler(myAuthenticationSuccessHandler)

Keep in mind that manipulating session data while the user is still using your service is not really a good idea, so I wouldn't recommend doing something like this unless you are absolutely required to.

  • Related