OAuth2 protected resources using RestTemplate

Upasana | May 05, 2019 | 2 min read | 2,825 views


An OAuth2 Authorization Server is responsible for issuing JWT accessToken/refreshToken when a resource owner presents its credentials. credentials typically consists of ClientId/ClientSecret, username/password, grant_type and scope of the request.

In this tutorial we will use RestTemplate library to hit the token endpoint on authorization server and generate the accessToken.

Issue AccessToken based on resource owner credentials
fun getSsoAccessToken(): String? {
    val restTemplate = RestTemplate()
    restTemplate.interceptors = listOf(RequestResponseLoggingInterceptor())

    val headers = HttpHeaders()
    headers.contentType = MediaType.APPLICATION_FORM_URLENCODED
    headers.accept = listOf(MediaType.APPLICATION_JSON)
    headers.setBasicAuth("<client-id>", "<client-secret>")

    val map = LinkedMultiValueMap<String, String>()
    map.add("grant_type", "password")
    map.add("scope", "openid")
    map.add("username", "<username>")
    map.add("password", "<password>")
    val request = HttpEntity<MultiValueMap<String, String>>(map, headers)
    val responseEntity = restTemplate.exchange("https://<base-url>/oauth/token", HttpMethod.POST, request, JsonNode::class.java)
    if(responseEntity.statusCode.is2xxSuccessful) {
        return responseEntity.body?.get("access_token")?.asText()
    } else {
        throw IllegalStateException("Error occurs during token generation")
    }
}
1 client-id and client-secret are basic credentials provided by OAuth2 Provider

Now this accessToken can be used to make calls to the protected resource server using the below syntax:

Making Call to actual service using recently acquired AccessToken
fun deleteAssessment(token: String?, id: String): String? {
    val headers = HttpHeaders()
    headers.add("Authorization", "bearer $token")
    headers.contentType = MediaType.APPLICATION_JSON
    val httpEntity = HttpEntity<String>(headers)
    val typeRef = object : ParameterizedTypeReference<ServiceResponse<JsonNode>>() {}
    val responseEntity = restTemplate.exchange("https://<base-url>/assessment/id/1", HttpMethod.DELETE, httpEntity, typeRef)
    if (responseEntity.statusCode.is2xxSuccessful) {
        println("Successfully deleted assessment: $questionnaireId")
        val response = responseEntity.body
        return response?.data?.toString()
    }
    return null
}
1 Passing the OAuth2 AccessToken in request.

That’s all!

If you are looking for same tutorial but using restassured, then follow this article- OAuth2 Login with Rest Assured Testcases


Top articles in this category:
  1. OAuth2 protected resources in RestAssured Testcases
  2. Rest Assured API Testing Interview Questions
  3. REST Assured Basic Authentication
  4. Junit interview questions for SDET automation engineer
  5. Java Coding Problems for SDET Automation Engineer
  6. 50 Java Interview Questions for SDET Automation Engineer
  7. Java 11 HttpClient with Basic Authentication

Recommended books for interview preparation:

Find more on this topic: