OAuth2 protected resources using RestTemplate

Carvia Tech | May 05, 2019 | 2 min read | 2,471 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. Rest Assured API Testing Interview Questions
  2. SDET: JUnit interview questions for automation engineer
  3. SDET Java Coding Challenges
  4. 50 SDET Java Interview Questions & Answers
  5. OAuth2 protected resources in RestAssured Testcases
  6. Commonly used Http methods in RESTful services
  7. Java 11 HttpClient with Basic Authentication

Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info