Skip to content
Advertisement

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

I have added JWT Authentication using Auth0 to my Spring Boot REST API following this example.

Now, as expected, my previously working Controller unit tests give a response code of401 Unauthorized rather than 200 OK as I am not passing any JWT in the tests.

How can I mock the JWT/Authentication part of my REST Controller tests?

Unit test class

JavaScript

Requests class (used above)

JavaScript

Spring Security Config

JavaScript

Abstract Unit test class

JavaScript

Advertisement

Answer

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:

JavaScript

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:

JavaScript

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:

JavaScript
Advertisement