spring-mvcsession-variablesspring-beanuserprincipal

How to access the logged-in Principal from a session scoped spring bean


I want to access the logged-in user from a session-scoped spring bean, is that possible?

I'm not using spring security, but openam instead to provide security to my web application, so I can't use this (as I've seen in many examples on the internet):

(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Is it possible to inject into my session-scoped bean the same name that you get from:

HttpServletRequest.getUserPrincipal().getName()

Solution

  • You can try creating an Interceptor and setting the logged in user to a property of your session bean, which can be injected into your interceptor.

    Like this:

    public class SessionDataInitializerInterceptor extends HandlerInterceptorAdapter {
    
        private static final Logger LOG = Logger.getLogger(SessionDataInitializerInterceptor.class);
    
        @Autowired
        SessionData sessionData;
    
        public SessionDataInitializerInterceptor() {
        }
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            Principal principal = request.getUserPrincipal();
            if (principal != null) {
                if (sessionData.getUser() == null) {
                    sessionData.setUser(principal.getName());
                }
            } else {
                LOG.error(String.format("No user principal in request for url[%s]", request.getRequestURL().toString()));
            }
            return true;
        }
    
    }
    

    Don't forget to map your interceptor to the appropriate URLs.