Okta Auth SDK Guide

On This Page

The Okta Auth SDK builds on top of our Authentication API and OpenID Connect API to enable you to create a fully branded sign-in experience using JavaScript.

The Okta Auth SDK is used by Okta's Sign-in Widget which powers the default Okta sign-in page. If you're building a JavaScript front end or Single Page App (SPA), the Auth SDK gives you added control and customization beyond what is possible with the Widget.

In this guide you will learn how to use the Auth SDK on a simple static page to:

  • Retrieve and store an OpenID Connect (OIDC) token (id_token)
  • Get an Okta session

Note: @okta/okta-auth-js version 4.5.0 or above is required to run samples in this guide.

If you'd like to explore the entire Auth SDK, please see the Okta AuthJS Source & API Reference (opens new window).

Prerequisites

You will need the following things for this guide:

Installation

Include the following script tag in your target web page:

<script src="https://global.oktacdn.com/okta-auth-js/4.5.0/okta-auth-js.min.js" type="text/javascript"></script>

Part 1: Retrieve and Store an OpenID Connect Token

In this first section you will learn how to:

  • Configure your Okta Auth SDK Client
  • Retrieve an ID Token using a redirect to your Okta org's sign-in page
  • Parse a token from the URL that results from the redirect
  • Store the parsed token inside the SDK's Token Manager
  • Retrieve the stored token from the Token Manager

If you'd like to see the complete code example, you can find it below.

Client Configuration

To initialize the SDK, create a new instance of the OktaAuth object:

var authClient = new OktaAuth({
  url: 'https://{yourOktaDomain}',
  clientId: '{clientId}',
  redirectUri: 'http://localhost:8080'
});

Replace each of these property values with ones from your Okta org and application. For more information about these properties, see the Client Configuration section of the Auth SDK reference (opens new window).

Retrieve ID Token from Okta

To retrieve an ID Token from Okta, you will use the token.getWithRedirect method, specifying that you want an id_token included in the response:

authClient.token.getWithRedirect({
  responseType: 'id_token'
});

Read more about getWithRedirect in the Auth SDK Reference (opens new window).

Parse the Token

After the redirect, the URL will contain an ID Token in the form of a JWT. The token.parseFromUrl method can be used to parse that token from the URL:

authClient.token.parseFromUrl()
  .then(res => {
    const { idToken } = res.tokens;
  })

You can also display a specific part of the parsed token:

console.log(`Hi ${idToken.claims.email}!`);

Read more about parseFromUrl in the Auth SDK Reference (opens new window).

Store the Parsed Token

Once the token has been parsed out of the URL, you can add it to the Token Manager using the tokenManager.add method:

authClient.tokenManager.add('idToken', idToken);

Read more about tokenManager.add in the Auth SDK Reference (opens new window).

The full code to parse the token, display the email from it, and then add it to the SDK's Token Manager looks like this:

authClient.token.parseFromUrl()
  .then(res => {
    const { idToken } = res.tokens;
    console.log(`Hi ${idToken.claims.email}!`);
    authClient.tokenManager.add('idToken', idToken);
  })

Retrieve the Stored Token

A token that is stored in the Token Manager can be retrieved using the tokenManager.get method:

authClient.tokenManager.get('idToken')
.then(function(token) {
  if (token) {
    // Token is valid
  } else {
    // Token has expired
  }
})

Read more about tokenManager.get in the Auth SDK Reference (opens new window).

Complete OpenID Connect Token Example

Putting it all together, the final example looks like this:

// Bootstrap the AuthJS Client
const authClient = new OktaAuth({
  // Org URL
  url: 'https://{yourOktaDomain}',
  // OpenID Connect APP Client ID
  clientId: '{clientId}',
  // Trusted Origin Redirect URI
  redirectUri: 'http://localhost:8080'
});

if (authClient.isLoginRedirect()) {
  // Parse token from redirect url
  authClient.token.parseFromUrl()
    .then(data => {
      const { idToken } = data.tokens;
      console.log(`Hi ${idToken.claims.email}!`);
      // Store parsed token in Token Manager
      authClient.tokenManager.add('idToken', idToken);
      console.log(idToken);
    });
} else {
  // Attempt to retrieve ID Token from Token Manager
  authClient.tokenManager.get('idToken')
    .then(idToken => {
      console.log(idToken);
      if (idToken) {
        console.log(`Hi ${idToken.claims.email}!`);
      } else {
        // You're not logged in, you need a sessionToken
        authClient.token.getWithRedirect({
          responseType: 'id_token'
        });
      }
    })
}

In the code example above, the ID Token is retrieved using a redirect to the Okta sign-in page. It is also possible to take a user-inputted username and password pair and pass them to the signIn method. This method then initiates an authentication process which returns an Okta session cookie. This Okta session cookie can then be used, along with the getWithRedirect method, to get back the ID Token. This means that there is no need to redirect the user to the Okta sign-in page.

Read more about signIn in the Auth SDK Reference (opens new window).

else {
  // You're not logged in, you need a sessionToken
  var username = prompt('What is your username?');
  var password = prompt('What is your password?');

  authClient.signInWithCredentials({username, password})
    .then(transaction => {
      if (transaction.status === 'SUCCESS') {
        authClient.token.getWithRedirect({
          sessionToken: transaction.sessionToken,
          responseType: 'id_token'
        });
      }
    });
}

Note: This example, like everything else on this page, is for illustrative purposes only. The prompt() method isn't considered a secure way of asking for user authentication credentials.

Complete Okta Session and OIDC Token Example

// Bootstrap the AuthJS Client
const authClient = new OktaAuth({
  // Org URL
  url: 'https://{yourOktaDomain}',
  // OpenID Connect APP Client ID
  clientId: '{clientId}',
  // Trusted Origin Redirect URI
  redirectUri: 'http://localhost:8080'
});

if (authClient.isLoginRedirect()) {
  // Parse token from redirect url
  authClient.token.parseFromUrl()
    .then(data => {
      const { idToken } = data.tokens;
      console.log(`Hi ${idToken.claims.email}!`);
      // Store parsed token in Token Manager
      authClient.tokenManager.add('idToken', idToken);
      console.log(idToken);
    });
} else {
  // Attempt to retrieve ID Token from Token Manager
  authClient.tokenManager.get('idToken')
    .then(idToken => {
      console.log(idToken);
      if (idToken) {
        console.log(`Hi ${idToken.claims.email}!`);
      } else {
        var username = prompt('What is your username?');
        var password = prompt('What is your password?');

        authClient.signInWithCredentials({username, password})
          .then(transaction => {
            if (transaction.status === 'SUCCESS') {
              authClient.token.getWithRedirect({
                sessionToken: transaction.sessionToken,
                responseType: 'id_token'
              });
            }
          });
      }
    });
}