小编use*_*970的帖子

@SpringBootTest OAuth2 JWT令牌授权仅在集成测试中失败

  • 具有JWT访问令牌认证和授权的Spring Boot,Spring Security OAuth2在完整服务器运行(在PostMan和Chrome中测试)中工作正常,但在集成测试中没有
  • @WithMockUser适用于Controller单元测试
  • @WithMockUser不适用于集成测试(我认为是因为访问令牌的JWT实现)
  • 设置RestTemplate交换调用以获取测试的访问令牌
  • 失败了 java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
  • 访问令牌获取代码:

    private String getAccessToken() throws Exception {
        String urlString = "/oauth/token";
        HttpEntity<MultiValueMap<String, String>> request = getAccessTokenRequest();
    
        ResponseEntity<JSONObject> responseEntity = restTemplate
                .exchange(urlString, HttpMethod.POST, request, JSONObject.class);
        assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
    
        JSONObject userJson = responseEntity.getBody();
        assertNotNull(userJson.get("access_token"));
        assertEquals("bearer", userJson.get("token_type"));
    
        return userJson.getString("access_token");
    }
    
    private HttpEntity<MultiValueMap<String, String>> getAccessTokenRequest() {
        HttpHeaders headers = new HttpHeaders();
        headers = setBasicAuthHeaders(headers);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    
        MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
        requestMap.add("grant_type", "client_credentials");
        return new HttpEntity<>(requestMap, …
    Run Code Online (Sandbox Code Playgroud)

rest spring integration-testing spring-security spring-boot

6
推荐指数
0
解决办法
659
查看次数