How to mock JWT authenticaiton in a Spring Boot Unit Test?

If I understand correctly your case there is one of the solutions.

In most cases, JwtDecoder bean performs token parsing and validation if the token exists in the request headers.

Example from your configuration:

    JwtDecoder jwtDecoder() {
        By default, Spring Security does not validate the "aud" 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)

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);


        return jwtDecoder;

So for the tests, you need to add stub of this bean and also for replacing this bean in spring context, you need the test configuration with it.

It can be some things like this:

public class TestSecurityConfig {

  static final String AUTH0_TOKEN = "token";
  static final String SUB = "sub";
  static final String AUTH0ID = "sms|12345678";

  public JwtDecoder jwtDecoder() {
    // This anonymous class needs for the possibility of using SpyBean in test methods
    // Lambda cannot be a spy with spring @SpyBean annotation
    return new JwtDecoder() {
      public Jwt decode(String token) {
        return jwt();

  public Jwt jwt() {

    // This is a place to add general and maybe custom claims which should be available after parsing token in the live system
    Map<String, Object> claims = Map.of(

    //This is an object that represents contents of jwt token after parsing
    return new Jwt(
        Map.of("alg", "none"),


For using this configuration in tests just pick up this test security config:

@SpringBootTest(classes = TestSecurityConfig.class)

Also in the test request should be authorization header with a token like Bearer .. something.

Here is an example regarding your configuration:

    public static RequestBuilder getAllRoundsByUserId(String userId) {

        return MockMvcRequestBuilders
            .get("/users/" + userId + "/rounds/")
            .header(HttpHeaders.AUTHORIZATION, "Bearer token"))