title: Spring - RESTful authentication using cookies
body: <p>I try to implement authentication (for my android client app) using cookies, based on this article -<a href="http://automateddeveloper.blogspot.co.uk/2014/03/securing-your-mobile-api-spring-security.html" rel="noreferrer">http://automateddeveloper.blogspot.co.uk/2014/03/securing-your-mobile-api-spring-security.html</a></p>
  
  <p>SecurityConfig:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      private final static String TOKEN_STRING = "my_token";
      private final static String COOKIE_STRING = "my_cookie";
  
      @Autowired
      private UserDetailsService userSvc;
      @Autowired
      private MyTokenBasedRememberMeService tokenSvc;
      @Autowired
      private RememberMeAuthenticationProvider rememberMeProvider;
      @Autowired 
      private MyAuthSuccessHandler authSuccess;
      @Autowired
      private MyAuthFailureHandler authFailure;
      @Autowired
      private MyLogoutSuccessHandler logoutSuccess;
  
  
      @Autowired
      protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth
              .userDetailsService(userSvc)
              .passwordEncoder(passwordEncoder());
  
          auth.authenticationProvider(rememberMeProvider);
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
           http
              .authorizeRequests()
                  .antMatchers("/register").permitAll()
                  .anyRequest().authenticated().and()
              .formLogin()
                 .loginPage("/")
                 .loginProcessingUrl("/loginendpoint")
                 .successHandler(authSuccess)
                 .failureHandler(authFailure).and()
              .logout()                           
                  .logoutUrl("/logout")
                  .logoutSuccess(logoutSuccess)
                  .deleteCookies(COOKIE_STRING).and()
              .rememberMe()
                  .rememberMeServices(tokenSvc).and()
              .csrf()
                  .disable()
              .addFilterBefore(rememberMeAuthenticationFilter(), BasicAuthenticationFilter.class)
              .sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Bean
      public RememberMeAuthenticationFilter rememberMeAuthenticationFilter() throws Exception {
          return new RememberMeAuthenticationFilter(authenticationManager(), tokenBasedRememberMeService());
      }
  
      @Bean
      public RememberMeAuthenticationProvider rememberMeAuthenticationProvider() {
          return new RememberMeAuthenticationProvider(TOKEN_STRING);
      }
  
      @Bean
      public MyTokenBasedRememberMeService tokenBasedRememberMeService() {
          MyTokenBasedRememberMeService service = new MyTokenBasedRememberMeService(TOKEN_STRING,
                  userSvc);
          service.setAlwaysRemember(true);
          service.setCookieName(COOKIE_STRING);
          return service;
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          PasswordEncoder encoder = new BCryptPasswordEncoder();
          return encoder;
      }
  
  }
  </code></pre>
  
  <p>MyTokenBasedRememberMeService:</p>
  
  <pre><code>public class MyTokenBasedRememberMeService extends TokenBasedRememberMeServices {
  
      private final static String TOKEN_STRING = "my_token";
  
      public MyTokenBasedRememberMeService(String key, UserDetailsService userDetailsService) {
          super(key, userDetailsService);
      }
  
      @Override
      protected String extractRememberMeCookie(HttpServletRequest request) {
          String token = request.getHeader(TOKEN_STRING);
          if ((token == null) || (token.length() == 0)) {
              return "";
          }
          return token;
      }
  }
  </code></pre>
  
  <p>Unfortunately after a successful login my cookie is empty on the client side:</p>
  
  <pre><code>Set-Cookie: my_cookie=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/
  </code></pre>
  
  <p>What's wrong? </p>
  
  <p><strong>-------EDIT 1-------</strong></p>
  
  <blockquote>
    <p>If you login directly in the browser you get no cookie (in dev tools for example)?</p>
  </blockquote>
  
  <p>I tested it using postman and I received only JSESSIONID cookie (no my_cookie).</p>
  
  <blockquote>
    <p>Also, are you using a custom login controller method? (e.g. Is your usercontroller explicitly authenticating users?)</p>
  </blockquote>
  
  <p>Yes, I'm using a custom login controller method, but I'm new in spring security and if can be done without a custom controller I will be grateful for any explanations. My controller is responsible for authentication of the user.</p>
  
  <blockquote>
    <p>If you are not using spring-security to handle authentication then I suspect you may have to explicitly set cookies etc yourself</p>
  </blockquote>
  
  <p>No, I'm using spring security only. At least I think so ... :)</p>
  
  <blockquote>
    <p>What is UserController login method doing?</p>
  </blockquote>
  
  <p>I updated my code.</p>
  
  <p><strong>-------EDIT 2-------</strong></p>
  
  <p>According to @rhinds advices and the spring documentation I corrected a few things (above code is updated). Now I can login to <code>loginendpoint</code> and after login I get <code>my_cookie</code>. But I have related questions:</p>
  
  <ol>
  <li>After a successful login I receive a cookie in response. To further requests I have to manually add the token (client side) if it's automatically added on the server side?</li>
  <li>What about logout? How "Spring" will know which user has to be logged out?</li>
  <li>What about the token expiration date? The default is 2 weeks, then what? Can I set so that the token never expires?</li>
  </ol>
  
  <p>For people who will be do something similar I recommend a look at this great article also - <a href="https://dzone.com/articles/secure-rest-services-using" rel="noreferrer">https://dzone.com/articles/secure-rest-services-using</a> :)</p>