@SpringBootTest OAuth2 JWT Token Authorization Only Finishes in Integration Tests

  • Spring Download, Spring OAuth2 security with authentication and authorization of the JWT access token works fine when the server starts completely (tested in PostMan and Chrome), but not in integration tests
  • @WithMockUser works for controller module tests
  • @WithMockUser does not work for integration tests (I think due to the JWT implementation for access tokens)
  • Configuring a RestTemplate exchange call to obtain an access token for tests
  • Crash with java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
  • Access Token Selection Code:

     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; } 
  • Integration test (always errors in the getAccessToken() function call):

     @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()); } 
  • Test class annotations:

     @ActiveProfiles("test") @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
+5
source share

Source: https://habr.com/ru/post/1260772/


All Articles