title: Spring Boot Unit Tests with JWT Token Security
body: <p>I am creating a backend using Spring Boot and I have just added JWT security to it.</p>
  
  <p>I have done some tests using a REST Client and the JWT security is working fine, however all of my unit tests are now returning a 403 error code.</p>
  
  <p>I've added the <code>@WithMockUser</code> annotation to them, but they are still not working:</p>
  
  <pre><code>@Test
  @WithMockUser
  public void shouldRedirectToInstaAuthPage() throws Exception {
      mvc.perform(MockMvcRequestBuilders.get("/instaAuth")).andExpect(status().is3xxRedirection());
  }
  </code></pre>
  
  <p>Is there some other configuration that I am missing here?</p>
  
  <p>Here is the security configuration:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class ServerSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Override
        protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable().authorizeRequests()
              .antMatchers("/").permitAll()
              .antMatchers(HttpMethod.POST, "/login").permitAll()
              .anyRequest().authenticated()
              .and()
              // We filter the api/login requests
              .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                      UsernamePasswordAuthenticationFilter.class)
              // And filter other requests to check the presence of JWT in header
              .addFilterBefore(new JWTAuthenticationFilter(),
                      UsernamePasswordAuthenticationFilter.class);
        }
  
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          // Create a default account
          auth.inMemoryAuthentication()
              .withUser("john")
              .password("123")
              .roles("ADMIN");
        }
  }
  </code></pre>
  
  <p>And Method security:</p>
  
  <pre><code>@Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
  public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
  
      @Override
      protected MethodSecurityExpressionHandler createExpressionHandler() {
          return new OAuth2MethodSecurityExpressionHandler();
      }
  
  }
  </code></pre>