Test annotation for mocking JWT authentication when testing MockMVC with WebTestClient. Workaround for issue introduced with spring security 5.3, details of which can be found here.
This annotation was heavily influenced by the work @rwinch did with the existing spring security test annotations, as well as the workaround he proposed in the above referenced issue.
<dependency>
<groupId>com.derplicity</groupId>
<artifactId>spring-security-test-addons</artifactId>
<version>0.1.2</version>
</dependency>
// Configure MockMvc
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebTestClientTests {
WebTestClient webTestClient;
// Create WebTestClient
@Autowired
void setMockMvc(MockMvc mockMvc) {
this.webTestClient = MockMvcWebTestClient.bindTo(mockMvc)
.build();
}
// Basic mocked JWT authentication token, no specific claims or authorities added.
@Test
@WithMockJwt
void exampleTest() {
webTestClient
.get()
.uri("/example")
.exchange()
.expectStatus().isOk();
}
// Subject of JWT can be changed via the `subject` member.
@Test
@WithMockJwt(subject = "changed-subject")
void exampleTest() {
webTestClient
.get()
.uri("/example")
.exchange()
.expectStatus().isOk();
}
// Authorities can be defined via a `String[]` assigned to `authorities` member.
@Test
@WithMockJwt(authorities = {"EXAMPLE1", "EXAMPLE2"})
void exampleTest() {
webTestClient
.get()
.uri("/example")
.exchange()
.expectStatus().isOk();
}
// Custom claims can be added to the JWT via the `claims` member. The member is a
// string and expects a JSON object which will be parsed and added to the claims.
// Malformed JSON will result in a `JsonParseException`.
@Test
@WithMockJwt(claims = """
{
"exampleClaim": "exampleValue"
}
""")
void exampleTest() {
webTestClient
.get()
.uri("/example")
.exchange()
.expectStatus().isOk();
}
}