title: Spring MVC + Spring Security login with a rest web service
body: <p>I have a SpringMVC web application that needs to authenticate to a RESTful web service using Spring Security by sending the username and password. When an user is logged, a cookie needs to be set to the user's browser and in the subsequent calls the user session is validated with another RESTful web service by using the cookie.</p>
  
  <p>I've been looking everywhere, but I have not been able to find a good example on how to accomplish this, and all my attempts have been in vain.</p>
  
  <p>Here is what I have in mind:</p>
  
  <p>I can have two authentication-providers declared, the first checks the cookie, and if it fails for any reason it goes to the second one which checks with the username and password (will fail too if there is no username and password in that request).</p>
  
  <p>Both services return the authorities of the user each time, and spring security is "stateless".</p>
  
  <p>On the other hand, I have questioned myself if this approach is correct, since it's been so difficult to find an example or somebody else with the same problem. Is this approach wrong?</p>
  
  <p>The reason why I want to do this instead of just JDBC authentication is because my whole web application is stateless and the database is always accessed through RESTful web services that wrap a "petitions queue", I'd like to respect this for user authentication and validation too.</p>
  
  <p>What have I tried so far? I could paste the long long springSecurity-context.xml, but I'll just list them instead for now:</p>
  
  <ol>
  <li>Use a custom authenticationFilter with a authenticationSuccessHandler. Obviously doesn't work because the user is already logged in this point.</li>
  <li>Make an implementation of entry-point-ref filter.</li>
  <li>Do a custom-filter in the position BASIC_AUTH_FILTER</li>
  <li>Make a custom Authentication Provider (Struggled a lot with no luck!). I'm retrying this while I get some answers.</li>
  <li>I was starting to use CAS when I decided to write a question instead. Maybe in the future I can consider having a CAS server in my webapp, however for the moment, this feels like a huge overkill.</li>
  </ol>
  
  <p>Thanks in advance!</p>
  
  <p>BTW, I'm using Spring Security 3.1.4 and Spring MVC 3.2.3</p>
  
  <p><strong>EDIT: I WAS ABLE TO DO IT THANKS TO @coder ANSWER</strong></p>
  
  <p>Here is some light on what I did, I'll try to document all this and post it here or in a blog post sometime soon:</p>
  
  <pre><code>&lt;http use-expressions="true" create-session="stateless" entry-point-ref="loginUrlAuthenticationEntryPoint"
          authentication-manager-ref="customAuthenticationManager"&gt;
      &lt;custom-filter ref="restAuthenticationFilter" position="FORM_LOGIN_FILTER" /&gt;
      &lt;custom-filter ref="restPreAuthFilter" position="PRE_AUTH_FILTER" /&gt;
      &lt;intercept-url pattern="/signin/**" access="permitAll" /&gt;
      &lt;intercept-url pattern="/img/**" access="permitAll" /&gt;
      &lt;intercept-url pattern="/css/**" access="permitAll" /&gt;
      &lt;intercept-url pattern="/js/**" access="permitAll" /&gt;
      &lt;intercept-url pattern="/**" access="hasRole('ROLE_USER')" /&gt;
  
  &lt;/http&gt;
  
  &lt;authentication-manager id="authManager" alias="authManager"&gt;
      &lt;authentication-provider ref="preauthAuthProvider" /&gt;
  &lt;/authentication-manager&gt;
  
  &lt;beans:bean id="restPreAuthFilter" class="com.company.CustomPreAuthenticatedFilter"&gt;
      &lt;beans:property name="cookieName" value="SessionCookie" /&gt;
      &lt;beans:property name="checkForPrincipalChanges" value="true" /&gt;
      &lt;beans:property name="authenticationManager" ref="authManager" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="preauthAuthProvider"
      class="com.company.CustomPreAuthProvider"&gt;
      &lt;beans:property name="preAuthenticatedUserDetailsService"&gt;
          &lt;beans:bean id="userDetailsServiceWrapper"
              class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"&gt;
              &lt;beans:property name="userDetailsService" ref="userDetailsService" /&gt;
          &lt;/beans:bean&gt;
      &lt;/beans:property&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="userDetailsService" class="com.company.CustomUserDetailsService" /&gt;
  
  &lt;beans:bean id="loginUrlAuthenticationEntryPoint"
      class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"&gt;
      &lt;beans:constructor-arg value="/signin" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="customAuthenticationManager"
      class="com.company.CustomAuthenticationManager" /&gt;
  
  &lt;beans:bean id="restAuthenticationFilter"
      class="com.company.CustomFormLoginFilter"&gt;
      &lt;beans:property name="filterProcessesUrl" value="/signin/authenticate" /&gt;
      &lt;beans:property name="authenticationManager" ref="customAuthenticationManager" /&gt;
      &lt;beans:property name="authenticationFailureHandler"&gt;
          &lt;beans:bean
              class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"&gt;
              &lt;beans:property name="defaultFailureUrl" value="/login?login_error=t" /&gt;
          &lt;/beans:bean&gt;
      &lt;/beans:property&gt;
  &lt;/beans:bean&gt;
  </code></pre>
  
  <p>And the Custom Implementations are something like this:</p>
  
  <pre><code>// Here, the idea is to write authenticate method and return a new UsernamePasswordAuthenticationToken
  public class CustomAuthenticationManager implements AuthenticationManager { ... }
  
  // Write attemptAuthentication method and return UsernamePasswordAuthenticationToken 
  public class CustomFormLoginFilter extends UsernamePasswordAuthenticationFilter { ... }
  
  // Write getPreAuthenticatedPrincipal and getPreAuthenticatedCredentials methods and return cookieName and cookieValue respectively
  public class CustomPreAuthenticatedFilter extends AbstractPreAuthenticatedProcessingFilter { ... }
  
  // Write authenticate method and return Authentication auth = new UsernamePasswordAuthenticationToken(name, token, grantedAuths); (or null if can't be pre-authenticated)
  public class CustomPreAuthProvider extends PreAuthenticatedAuthenticationProvider{ ... }
  
  // Write loadUserByUsername method and return a new UserDetails user = new User("hectorg87", "123456", Collections.singletonList(new GrantedAuthorityImpl("ROLE_USER")));
  public class CustomUserDetailsService implements UserDetailsService { ... }
  </code></pre>