How to get idToken or accessToken via the API?

Essentially the question. I would like to get a user’s tokens via API calls, not by actually logging in with the browser. I have tried calling the /api/v1/authn API, which gives me the sessionToken, but when I try to exchange it for an idToken or accessToken through the /v1/authorize API, I get a 403 error when I use Postman, but it works with the callback URL when I use the browser.

Maybe this helps.

Here is an example in Python which exchanges the token, which can be found here

    query_params = requests.compat.urlencode(query_params)
    exchange = requests.post(
        config["token_uri"],
        headers=headers,
        data=query_params,
        auth=(config["client_id"], config["client_secret"]),
    ).json()

    # Get tokens and validate
    if not exchange.get("token_type"):
            return "Unsupported token type. Should be 'Bearer'.", 403
    access_token = exchange["access_token"]
    id_token = exchange["id_token"]

This is about as much as I can help you as I’m no expert.
But answering those questions will help anyone better understand your situation.

1 Like

Thank you for your response!

I am not sure which flow methods I’m using.

I’ve not seen that.

I’m using Python, though Javascript examples are also acceptable since I have a SPA that needs it too.

The main thing with this example is that it still uses the redirect to get the “code” first, and then exchanges that with the OIDC tokens (see below screenshot of the example). I would like to be able to do all of it without this redirect in the first place, just through API calls ideally.

Okay, looks like you may want to look at the JavaScript QuickStart guides found here
Quickstart | Okta Developer which all talk about SPA sites and the Redirect Model. They all use one or more OKTA JavaScript library.

However, before that I suggest that you read this page OAuth 2.0 and OpenID Connect overview | Okta Developer especially ‘what-kind-of-client-are-you-building’ - OAuth 2.0 and OpenID Connect overview | Okta Developer.

The screen shot that you have provided is for the Redirect Model with Authorization Code flow with PKCE (using Python), not to be confused with Authorization Code flow (using Python) and these two are different. I did confuse the two and ended up wasting a lot of time.
Also note that some flows provide an ID Token and Access Token, while others only provide an Access Token.
In the end, what helped me the most is getting the QuickStart working by itself and then copying the parts I needed to my real application.

1 Like

You may want to also checkout out the list of endpoints available to you by going to
https://{oktaDomain}/oauth2/default/.well-known/oauth-authorization-server

1 Like

Thank you so much Pete! This helped a lot! I was actually looking for the /token route, as described here.

The last link you sent was instrumental to finding what I wanted. What I needed was the resource owner password flow. This allows me to submit the username and password in exchange for the idToken and accessToken.

It’s great that you are on your way to a solution and I was glad that I was able to help.
I hope that you saw this
'About the Resource Owner Password grant

The Resource Owner Password flow isn’t a recommended approach. It’s intended for applications for which no other flow works, as it requires your application code to be fully trusted and protected from credential-stealing attacks. It’s made available primarily to provide a consistent and predictable integration pattern for legacy applications that can’t otherwise be updated to a more secure flow such as the Authorization Code flow. This should be your last option, not your first choice.’

Seeing as what you are creating is something new, maybe you should not use the Resource Owner Password flow.

1 Like

Hi Pete! Thank you for your responses, they are always insightful, and this is definitely something I will keep in mind.

Maybe I should have provided context on my case. The purpose of this question is not for a public-facing web app. Rather, it is for a tool used by internal/private stakeholders who are technical (ie. know how to code) but don’t necessarily have extensive knowledge on software development practices, such as scientists and engineers.

On another note, the python code I made for this is shown below:

import os
import requests
from base64 import b64encode

def authenticate(username, password):
  url = os.environ['OKTA_ORG_URL'] + '/oauth2/v1/token'

  payload = requests.compat.urlencode({
    'grant_type': 'password',
    'scope': 'openid',
    'username': username,
    'password': password
  })

  auth = f"{os.environ['OKTA_CLIENT_ID']}:{os.environ['OKTA_CLIENT_SECRET']}"

  headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic ' + b64encode(auth.encode()).decode()
  }

  response = requests.request("POST", url, headers=headers, data=payload)
  return response.json()

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.