All the information is available through HttpServletRequest
. You can obtain it by:
Dependency injection
The easiest way would be to inject servlet request directly into your UserDetailsService:
class:
public MyDetailsService implements UserDetailsService {
@Autowired
private HttpServletRequest request;
//...
}
or
public MyDetailsService implements UserDetailsService {
@Autowired
private HttpServletRequest request;
public UserDetails loadUserByUsername(String username){
HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest();
}
}
Remember to add the following listener to your web.xml
if you are not spring boot:
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
If you are using spring boot, add below this.
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
UPDATE: This works because Spring injects special scoped proxy implementing HttpServletRequest
, so you are able to access request-scoped request "bean" from singleton-scoped MyDetailsService
. Under the hood every call to request
's parameters is routed to org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder
ThreadLocal
which you can also access directly. As you can see Spring is very flexible when it comes to scoping rules. It just works.
RequestContextHolder
Another approach is to use RequestContextHolder
:
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.
currentRequestAttributes()).
getRequest();
Further reading: