title: Testing login in Spring Security
body: <p>I just started using Spring boot and Java Based Spring Configurations and I have a problem when trying to test security-related methods such as login and logout.</p>
  
  <p>I have the following configurations in my project</p>
  
  <p>SecurityConfig.java:</p>
  
  <pre><code>@EnableWebSecurity
  @Configuration
  @EnableGlobalMethodSecurity(prePostEnabled=true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .httpBasic()
              .authenticationEntryPoint(authenticationEntryPoint())
          .and()
              .formLogin()
              .successHandler(authenticationSuccessHandler())
              .failureHandler(authenticationFailureHandler())
          .and()
              .logout()
          .and()
              .authorizeRequests()
              .antMatchers("/login", "j_spring_security_check", "/register", "/logout").permitAll()
              .antMatchers("/**").hasRole("USER");
      }
      @Autowired
      protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
              .withUser("guest").password("guest").roles("USER");
      }
      @Bean
      public AuthenticationSuccessHandler authenticationSuccessHandler() {
           return new RestAuthenticationSuccessHandler();
      }
      @Bean
      public AuthenticationFailureHandler authenticationFailureHandler() {
          return new SimpleUrlAuthenticationFailureHandler();
      }
      @Bean
      public AuthenticationEntryPoint authenticationEntryPoint() {
          return new RestAuthenticationEntryPoint();
      }
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  }
  </code></pre>
  
  <p>SecurityWebAppInitializer.java</p>
  
  <pre><code>@Order(1)
  public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer { }
  </code></pre>
  
  <p>RestAuthenticationSuccessHandler.java</p>
  
  <pre><code>public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
  
  private RequestCache requestCache = new HttpSessionRequestCache();
  
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                      Authentication authentication) throws ServletException, IOException {
      SavedRequest savedRequest = requestCache.getRequest(request, response);
  
      if (savedRequest == null) {
          clearAuthenticationAttributes(request);
          return;
      }
      String targetUrlParam = getTargetUrlParameter();
      if (isAlwaysUseDefaultTargetUrl() ||
              (targetUrlParam != null &amp;&amp;
                      StringUtils.hasText(request.getParameter(targetUrlParam)))) {
          requestCache.removeRequest(request, response);
          clearAuthenticationAttributes(request);
          return;
      }
  
      clearAuthenticationAttributes(request);
  }
  
  public void setRequestCache(RequestCache requestCache) {
      this.requestCache = requestCache;
  }
  }
  </code></pre>
  
  <p>Now, I want to test the login process so my test class is the following:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(classes = { SecurityWebAppInitializer.class, SecurityConfig.class })
  public class SecurityTests {
  
  private MockMvc mockMvc;
  
  @Autowired
  private FilterChainProxy filterChainProxy;
  
  @Before
  public void setup() {
      mockMvc = MockMvcBuilders.standaloneSetup(SecurityWebAppInitializer.class, SecurityConfig.class).addFilters(filterChainProxy).build();
  }
  
  @Test
  public void thatLoginWithCorrectCredentialsWorks() throws Exception {
      mockMvc.perform(post("/j_spring_security_check")
              .param("j_username", "guest")
              .param("j_password", "guest")
      ).andExpect(status().isOk());
  }
  }
  </code></pre>
  
  <p>The above test returns the following error </p>
  
  <pre><code>java.lang.AssertionError: Status 
  Expected :200
  Actual   :403
  </code></pre>
  
  <p>which says that the user is forbidden to access the login page. However I don't get why as I've configured in the SpringConfig that a user with the above credentials is allowed to login to my application. I would like to apologise in advance in case my question is silly but I am still trying to improve my knowledge on that framework as I am using it only for a couple of weeks.</p>
  
  <p>EDIT: When I am using CURL to login I am getting the following error:</p>
  
  <blockquote>
    <p>{"timestamp":1401633376720,"error":"Forbidden","status":403,"message":"Expected CSRF token not found. Has your session expired?"}</p>
  </blockquote>