How can I access the HttpServletRequest object during user authentication in Spring Security?

There's a very similar question in the Spring Security FAQ.

You can inject a custom AuthenticationDetailsSource into the authentication filter to extract additional relevant information from the incoming request. This information can then be obtained from the submitted Authentication object in a custom AuthenticationProvider.


One of possible solutions is to use RequestContextFilter. You can define it in web.xml as on the following snippet:

<filter>
  <filter-name>requestContextFilter</filter-name>
  <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>requestContextFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

or if you just need it for some security issues then the better place is to put it to Spring Security config file, as on the following example:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <http>
    <custom-filter ref="requestContextFilter" before="FORM_LOGIN_FILTER"/>
    <form-login login-page="/login" authentication-failure-url="/login?error=failed" />
  </http>
  <beans:bean id="requestContextFilter" class="org.springframework.web.filter.RequestContextFilter"/>

  <authentication-manager alias="authManager">
    <authentication-provider ref="authProvider" />
  </authentication-manager>
  <beans:bean id="authProvider" class="my.company.CustomAuthProvider" />
</beans:beans>

Then you can use RequestContextHolder.currentRequestAttributes() method in Spring Security classes. For example as follows:

public class CustomAuthProvider extends DaoAuthenticationProvider {
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    System.err.println(attr.getRequest().getParameter("myParameterName"));
    return super.authenticate(authentication);
  }
}