0

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()
Henrique Ordine
  • 3,337
  • 4
  • 44
  • 70

2 Answers2

1

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.

Pearl Jade
  • 716
  • 1
  • 8
  • 22
1

Also this works:

@Component
@SessionScope
public class SessionData {

    @Autowired
    private HttpServletRequest request;

    @PostConstruct
    public void init() {
        Principal principal = request.getUserPrincipal();        
    }
}
xonya
  • 2,146
  • 29
  • 37