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

时间:2016-12-04 04:24:54

标签: spring rest spring-security spring-boot integration-testing

  • Spring Boot,具有JWT访问令牌认证和授权的Spring Security OAuth2在完整服务器运行(在PostMan和Chrome中测试)中工作正常但在集成测试中没有工作
  • @WithMockUser适用于控制器单元测试
  • @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, headers);
    }
    
    private HttpHeaders setBasicAuthHeaders(HttpHeaders headers) {
        String authorization = "Basic " + new String(Base64Utils.encode("test:testsecret".getBytes()));
        headers.add("Authorization", authorization);
        return headers;
    }
    
  • 集成测试(getAccessToken()函数调用中的始终错误):

    @Test
    public void createCustomer() throws Exception {
        String accessToken = getAccessToken();
    
        HttpHeaders headers = new HttpHeaders();
        headers.add("Bearer", accessToken);
        HttpEntity<String> entity = new HttpEntity<>(headers);
    
        ResponseEntity<Customer> responseEntity = restTemplate
                .exchange("/api/2.0/customers/save"+
                        "?firstName=" + customerToSave.getFirstName() +
                        "&lastName=" + customerToSave.getLastName(),
                        HttpMethod.GET, entity, Customer.class);
    
        Customer customer = responseEntity.getBody();
        assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
        assertEquals(customerToSave.getLastName(), customer.getLastName());
    }
    
  • 测试类注释:

    @ActiveProfiles("test")
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    

0 个答案:

没有答案