Reputation: 437
I've created an account on OKTA environment here. I searched on the net, but I couldn't find any examples on how to get access token from OKTA API. I'm looking for some example in "plain" Java code. But if there is something in any SDK, I'll be happy. I tried to create an HTTP request (POST), to /token endpoint. I've used cliend_id and client_secret - in body. I've also tried to put in into header as basic authentication (before that, I encoded client_id:client_secret with Base64), but I still getting unauthorized (401).
Upvotes: 1
Views: 4295
Reputation: 437
OK I have a solution. The problem was wrong configuration on OKTA. For those who needs working example, I'll share my tested code (believe me, it works)
public String GetToken() throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("https://YOUR_OKTA_DOMAIN/oauth2/default/v1/token"))
.headers("Content-type", "application/x-www-form-urlencoded",
"Authorization", "Basic " + Base64.getEncoder().encodeToString("CLIENT_ID:CLIENT_SECRET".getBytes()),
"Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"&grant_type=client_credentials" ))
.build();
HttpResponse<?> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return response.body().toString();
}
On Okta you need to have created additional scope for Authorization Server. This scope should be default, or if you don't want to set default scope, you have to add it in body as
.POST(HttpRequest.BodyPublishers.ofString(
"&grant_type=client_credentials" +
"scope=SCOPE_NAME"))
Upvotes: 5