Java tips and tricks from a lady trying to play with the boys...

Tuesday, June 9, 2015

Accessing HttpServletRequest in Spring UserDetailsService (with Annotations)

Using Spring 4.1.5 (but probably later versions of spring). You may have a requirement of getting information from the HTTP Request while your user is logging in using Spring Security. UserDetailsService is an interface, which you may have implemented in order to lookup the username, but loadUserByUsername only takes a String. How do we get the HttpServletRequest?

In your configuration, you should have set up a filter for Spring Security. You'll find this in your SpringWebAppInitializer. The method getServletFilters() should already have been set up with this. You will need to add a RequestContextFilter here before the Spring Security Filter. This will expose the HTTP Request.

@Override protected Filter[] getServletFilters() { 
return new Filter[]{ 
new RequestContextFilter(),
new DelegatingFilterProxy("springSecurityFilterChain")
}; 
}  

After doing this, you should be able to inject the HttpServletRequest right into your UserDetailsService:

@Autowired

private HttpServletRequest request;

That's it!
So easy, but documentation is lacking.