title: How to mock JWT authentication in a Spring Boot Unit Test?
body: <p>I have added JWT Authentication using Auth0 to my Spring Boot REST API following <a href="https://auth0.com/docs/quickstart/backend/java-spring-security5/02-using#calling-the-api-from-your-application" rel="nofollow noreferrer">this example</a>.</p>
  <p>Now, as expected, my previously working <code>Controller</code> unit tests give a response code of<code>401 Unauthorized</code> rather than <code>200 OK</code> as I am not passing any JWT in the tests.</p>
  <p>How can I mock the <code>JWT/Authentication</code> part of my REST Controller tests?</p>
  <h4>Unit test class</h4>
  <pre class="lang-java prettyprint-override"><code>@AutoConfigureMockMvc
  public class UserRoundsControllerTest extends AbstractUnitTests {
  
      private static String STUB_USER_ID = &quot;user3&quot;;
      private static String STUB_ROUND_ID = &quot;7e3b270222252b2dadd547fb&quot;;
  
      @Autowired
      private MockMvc mockMvc;
  
      private Round round;
  
      private ObjectId objectId;
  
      @BeforeEach
      public void setUp() {
          initMocks(this);
          round = Mocks.roundOne();
          objectId = Mocks.objectId();
      }
  
      @Test
      public void shouldGetAllRoundsByUserId() throws Exception {
  
          // setup
          given(userRoundService.getAllRoundsByUserId(STUB_USER_ID)).willReturn(
                  Collections.singletonList(round));
  
          // mock the rounds/userId request
          RequestBuilder requestBuilder = Requests.getAllRoundsByUserId(STUB_USER_ID);
  
          // perform the requests
          MockHttpServletResponse response = mockMvc.perform(requestBuilder)
                  .andReturn()
                  .getResponse();
  
          // asserts
          assertNotNull(response);
          assertEquals(HttpStatus.OK.value(), response.getStatus());
      }
  
      //other tests
  }
  </code></pre>
  <h4>Requests class (used above)</h4>
  <pre class="lang-java prettyprint-override"><code>public class Requests {
  
      private Requests() {}
  
      public static RequestBuilder getAllRoundsByUserId(String userId) {
          return MockMvcRequestBuilders
                  .get(&quot;/users/&quot; + userId + &quot;/rounds/&quot;)
                  .accept(MediaType.APPLICATION_JSON)
                  .contentType(MediaType.APPLICATION_JSON);
      }
  }
  </code></pre>
  <h4>Spring Security Config</h4>
  <pre class="lang-java prettyprint-override"><code>/**
   * Configures our application with Spring Security to restrict access to our API endpoints.
   */
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Value(&quot;${auth0.audience}&quot;)
      private String audience;
  
      @Value(&quot;${spring.security.oauth2.resourceserver.jwt.issuer-uri}&quot;)
      private String issuer;
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
              /*
              This is where we configure the security required for our endpoints and setup our app to serve as
              an OAuth2 Resource Server, using JWT validation.
              */
  
          http.cors().and().csrf().disable().sessionManagement().
                  sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                  .mvcMatchers(HttpMethod.GET, &quot;/users/**&quot;).authenticated()
                  .mvcMatchers(HttpMethod.POST, &quot;/users/**&quot;).authenticated()
                  .mvcMatchers(HttpMethod.DELETE, &quot;/users/**&quot;).authenticated()
                  .mvcMatchers(HttpMethod.PUT, &quot;/users/**&quot;).authenticated()
                  .and()
                  .oauth2ResourceServer().jwt();
      }
  
      @Bean
      JwtDecoder jwtDecoder() {
              /*
              By default, Spring Security does not validate the &quot;aud&quot; claim of the token, to ensure that this token is
              indeed intended for our app. Adding our own validator is easy to do:
              */
  
          NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
                  JwtDecoders.fromOidcIssuerLocation(issuer);
  
          OAuth2TokenValidator&lt;Jwt&gt; audienceValidator = new AudienceValidator(audience);
          OAuth2TokenValidator&lt;Jwt&gt; withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
          OAuth2TokenValidator&lt;Jwt&gt; withAudience = new DelegatingOAuth2TokenValidator&lt;&gt;(withIssuer,
                  audienceValidator);
  
          jwtDecoder.setJwtValidator(withAudience);
  
          return jwtDecoder;
      }
  
      @Bean
      CorsConfigurationSource corsConfigurationSource() {
          CorsConfiguration configuration = new CorsConfiguration();
          configuration.setAllowedOrigins(Arrays.asList(&quot;*&quot;));
          configuration.setAllowedMethods(Arrays.asList(&quot;*&quot;));
          configuration.setAllowedHeaders(Arrays.asList(&quot;*&quot;));
          configuration.setAllowCredentials(true);
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          source.registerCorsConfiguration(&quot;/**&quot;, configuration);
          return source;
      }
  }
  </code></pre>
  <h4>Abstract Unit test class</h4>
  <pre class="lang-java prettyprint-override"><code>@ExtendWith(SpringExtension.class)
  @SpringBootTest(
          classes = PokerStatApplication.class,
          webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
  )
  public abstract class AbstractUnitTests {
      // mock objects etc
  }
  </code></pre>