Java OAuth 2.0 get access token

Sašo Pavlič picture Sašo Pavlič · Nov 23, 2018 · Viewed 11.1k times · Source

I want to get access token OAuth 2.0 from REST API via Java code, the thing is that I've managed to successfully get it back from the server with Bash script (curl command)

Bash script (working):

#!/usr/bin/env bash

       # Base URL of TeamForge site.
       site_url="https://teamforge.example.com"

       # TeamForge authentication credentials.
       username="foo"
       password="bar"

       # Requested scope (all)
       scope="urn:ctf:services:ctf

       curl -d "grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password" $site_url/sf/auth/token

With that code snippet I'got this response:

  {
         "access_token": "eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1ZCI...",
         "token_type": "Bearer"
       }

When I've tried to translate it to Java code using Unirest :

  HttpResponse<JsonNode> jsonResponse = Unirest.post("\"https://teamforge.example.com/sf/auth/token")
                .header("accept", "application/json")
                .body("{\"grant_type\":\"password\"," +
                        "\"client_id\":\"api-client\", " +
                        "\"scope\":\"urn:ctf:services:ctf\"," +
                        "\"username\":\"foo\"," +
                        "\"password\":\"bar\"}")

                .asJson();

        System.out.println(jsonResponse.getBody());

Response was:

{"error_description":"Invalid grant","error":"invalid_grant"}

After a couple of researches and tries, I still don't know what am I missing in my Java code request. Can someone help me to add missing stuff or guide me to right directions?

CollabNet docs:

Saso

Answer

Hhovhann picture Hhovhann · Jan 9, 2019

Please try:

JsonNode jsonResponse = Unirest.post("https://teamforge.example.com/sf/auth/token")
.header("Content-Type", "application/json")
.field("scope", "urn:ctf:services:ctf")
.field("client_id", "api-client")
.field("grant_type", "password")
.field("username", "foo")
.field("password", "bar")
.asJson()
.getBody();

And one more question are you sure about grant type ?
grant_type = client_credentials maybe you need something like this.