title: Spring Security - Token based API auth & user/password authentication
body: <p>I am trying to create a webapp that will primarily provide a REST API using Spring, and am trying to configure the security side.</p>
  
  <p>I am trying to implement this kind of pattern: <a href="https://developers.google.com/accounts/docs/MobileApps" rel="nofollow noreferrer">https://developers.google.com/accounts/docs/MobileApps</a> (Google have totally changed that page, so no longer makes sense - see the page I was referring to here: <a href="http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps" rel="nofollow noreferrer">http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps</a>)</p>
  
  <p>Here is what I need to accompish:</p>
  
  <ul>
  <li>Web app has simple sign-in/sign-up forms that work with normal spring user/password authentication (have done this type of thing before with dao/authenticationmanager/userdetailsservice etc)</li>
  <li>REST api endpoints that are stateless sessions and every request authenticated based ona token provided with the request</li>
  </ul>
  
  <p>(e.g. user logins/signs up using normal forms, webapp provides secure cookie with token that can then be used in following API requests)</p>
  
  <p>I had a normal authentication setup as below:</p>
  
  <pre><code>@Override protected void configure(HttpSecurity http) throws Exception {
      http
          .csrf()
              .disable()
          .authorizeRequests()
              .antMatchers("/resources/**").permitAll()
              .antMatchers("/mobile/app/sign-up").permitAll()
              .antMatchers("/v1/**").permitAll()
              .anyRequest().authenticated()
              .and()
          .formLogin()
              .loginPage("/")
              .loginProcessingUrl("/loginprocess")
              .failureUrl("/?loginFailure=true")
              .permitAll();
  }
  </code></pre>
  
  <p>I was thinking of adding a pre-auth filter, that checks for the token in the request and then sets the security context (would that mean that the normal following authentication would be skipped?), however, beyond the normal user/password I have not done too much with token based security, but based on some other examples I came up with the following:</p>
  
  <p>Security Config:</p>
  
  <pre><code>@Override protected void configure(HttpSecurity http) throws Exception {
          http
              .csrf()
                  .disable()
              .addFilter(restAuthenticationFilter())
                  .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                  .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
                  .antMatcher("/v1/**")
              .authorizeRequests()
                  .antMatchers("/resources/**").permitAll()
                  .antMatchers("/mobile/app/sign-up").permitAll()
                  .antMatchers("/v1/**").permitAll()
                  .anyRequest().authenticated()
                  .and()
              .formLogin()
                  .loginPage("/")
                  .loginProcessingUrl("/loginprocess")
                  .failureUrl("/?loginFailure=true")
                  .permitAll();
      }
  </code></pre>
  
  <p>My custom rest filter:</p>
  
  <pre><code>public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  
      public RestAuthenticationFilter(String defaultFilterProcessesUrl) {
          super(defaultFilterProcessesUrl);
      }
  
      private final String HEADER_SECURITY_TOKEN = "X-Token"; 
      private String token = "";
  
  
      @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          HttpServletRequest request = (HttpServletRequest) req;
          HttpServletResponse response = (HttpServletResponse) res;
  
          this.token = request.getHeader(HEADER_SECURITY_TOKEN);
  
          //If we have already applied this filter - not sure how that would happen? - then just continue chain
          if (request.getAttribute(FILTER_APPLIED) != null) {
              chain.doFilter(request, response);
              return;
          }
  
          //Now mark request as completing this filter
          request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
  
          //Attempt to authenticate
          Authentication authResult;
          authResult = attemptAuthentication(request, response);
          if (authResult == null) {
              unsuccessfulAuthentication(request, response, new LockedException("Forbidden"));
          } else {
              successfulAuthentication(request, response, chain, authResult);
          }
      }
  
      /**
       * Attempt to authenticate request - basically just pass over to another method to authenticate request headers 
       */
      @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
          AbstractAuthenticationToken userAuthenticationToken = authUserByToken();
          if(userAuthenticationToken == null) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
          return userAuthenticationToken;
      }
  
  
      /**
       * authenticate the user based on token, mobile app secret &amp; user agent
       * @return
       */
      private AbstractAuthenticationToken authUserByToken() {
          AbstractAuthenticationToken authToken = null;
          try {
              // TODO - just return null - always fail auth just to test spring setup ok
              return null;
          } catch (Exception e) {
              logger.error("Authenticate user by token error: ", e);
          }
          return authToken;
      }
  </code></pre>
  
  <p>The above actually results in an error on app startup saying: <code>authenticationManager must be specified</code>
  Can anyone tell me how best to do this - is a pre_auth filter the best way to do this?</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>I wrote up what I found and how I did it with Spring-security (including the code) implementing a standard token implementation (not OAuth)</p>
  
  <p><a href="https://automateddeveloper.blogspot.co.uk/2014/03/securing-your-api-for-mobile-access.html" rel="nofollow noreferrer">Overview of the problem and approach/solution</a></p>
  
  <p><a href="https://automateddeveloper.blogspot.co.uk/2014/03/securing-your-mobile-api-spring-security.html" rel="nofollow noreferrer">Implementing the solution with Spring-security</a></p>
  
  <p>Hope it helps some others..</p>