Skip to content

Latest commit

 

History

History
101 lines (79 loc) · 3.62 KB

README.md

File metadata and controls

101 lines (79 loc) · 3.62 KB

spring-security-test-addons

Maven Central CircleCI DeepSource Security Score Known Vulnerabilities

Description

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.

Usage

Dependency

<dependency>
    <groupId>com.derplicity</groupId>
    <artifactId>spring-security-test-addons</artifactId>
    <version>0.1.2</version>
</dependency>

Examples

// 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();
    }
}