spring-projects / spring-restdocs

Test-driven documentation for RESTful services
https://spring.io/projects/spring-restdocs
Apache License 2.0
1.16k stars 734 forks source link

Using JWT Token to Access Resource Server #919

Closed sdack-cloud closed 7 months ago

sdack-cloud commented 7 months ago

resource server

    JwtAuthenticationToken authentication = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

I passed TOKEN during the request

There is a token value in HttpServletRequest, But JwtAuthenticationToken is null

    @BeforeEach
    void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .apply(documentationConfiguration(restDocumentation))
                .alwaysDo(print())
                .build();
    }
        this.mockMvc.perform(post("/user")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .header(HttpHeaders.AUTHORIZATION,token)
                .content("{}")
        )
                .andExpect(status().isOk())
sdack-cloud commented 7 months ago

org.springframework.restdocs:spring-restdocs-mockmvc:3.0.1

wilkinsona commented 7 months ago

This doesn't really have anything to do with Spring REST Docs as you'd see the same behavior with MockMvc alone. You need to configure MockMvc to interact with Spring Security as described in the Spring Security documentation.