- Release status
- Need help?
- Getting started
- Usage guide
- Strategies for Obtaining Tokens
- Configuration reference
- API Reference
- Building the SDK
- Node JS and React Native Usage
- Migrating from previous versions
- Contributing
The Okta Auth JavaScript SDK builds on top of our Authentication API and OpenID Connect & OAuth 2.0 API to enable you to create a fully branded sign-in experience using JavaScript.
You can learn more on the Okta + JavaScript page in our documentation.
This library uses semantic versioning and follows Okta's library version policy.
✔️ The current stable major version series is: 4.x
Version | Status |
---|---|
5.x |
✔️ Stable |
4.x |
|
3.x |
|
2.x |
❌ Retired |
1.x |
❌ Retired |
0.x |
❌ Retired |
The latest release can always be found on the releases page.
If you run into problems using the SDK, you can:
- Ask questions on the Okta Developer Forums
- Post issues here on GitHub (for code errors)
Users migrating from version 4.x of this SDK should see Migrating from 4.x to learn what changes are necessary.
This SDK is known to work with current versions of Chrome, Firefox, and Safari on desktop and mobile.
Compatibility with IE 11 / Edge can be accomplished by adding polyfill/shims for the following objects:
- ES Promise
- Array.from
- TextEncoder
- Object.assign
- UInt8 typed array
- webcrypto (crypto.subtle)
⚠️ crypto polyfills are unable to use the operating system as a source of good quality entropy used to generate pseudo-random numbers that are the key to good cryptography. As such we take the posture that crypto polyfills are less secure and we advise against using them.
This module provides an entrypoint that implements all required polyfills.
If you are using the JS on a web page from the browser, you can copy the node_modules/@okta/okta-auth-js/dist
contents to publicly hosted directory, and include a reference to the okta-auth-js.polyfill.js
file in a <script>
tag. It should be loaded before any other scripts which depend on the polyfill.
If you're using a bundler like Webpack or Browserify, you can simply import import or require @okta/okta-auth-js/polyfill
at or near the beginning of your application's code:
import '@okta/okta-auth-js/polyfill';
or
require('@okta/okta-auth-js/polyfill');
The built polyfill bundle is also available on our global CDN. Include the following script in your HTML file to load before any other scripts:
<script src="https://global.oktacdn.com/okta-auth-js/5.2.2/okta-auth-js.polyfill.js" type="text/javascript"></script>
⚠️ The version shown in this sample may be older than the current version. We recommend using the highest version available
Many browsers have started blocking cross-origin or "third party" cookies by default. Although most of the Okta APIs supported by this SDK do not rely upon cookies, there are a few methods which do. These methods will break if third party cookies are blocked:
- session APIs require access to cookies stored on the Okta domain.
- token
- token.getWithoutPrompt must have access to cookies on the Okta domain via an iFrame running on your application's page.
- token.renew uses token.getWithoutPrompt and is subject to the same limitations.
If your application depends on any of these methods, you should try to either rewrite your application to avoid using these methods or communicate to your users that they must enable third party cookies. Okta engineers are currently working on a better long-term solution to this problem.
Installing the Authentication SDK is simple. You can include it in your project via our npm package, @okta/okta-auth-js.
You'll also need:
- An Okta account, called an organization (sign up for a free developer organization if you need one)
- An Okta application, which can be created using the Okta Admin UI
When creating a new Okta application, you can specify the application type. This SDK is designed to work with SPA
(Single-page Applications) or Web
applications. A SPA
application will perform all logic and authorization flows client-side. A Web
application will perform authorization flows on the server.
From the Okta Admin UI, click Applications
, then select your application. You can view and edit your Okta application's configuration under the application's General
tab.
A string which uniquely identifies your Okta application.
To sign users in, your application redirects the browser to an Okta-hosted sign-in page. Okta then redirects back to your application with information about the user. You can learn more about how this works on Okta-hosted flows.
You need to whitelist the login redirect URL in your Okta application settings.
After you sign users out of your app and out of Okta, you have to redirect users to a specific location in your application. You need to whitelist the post sign-out URL in your Okta application settings.
Using our npm module is a good choice if:
- You have a build system in place where you manage dependencies with npm.
- You do not want to load scripts directly from third party sites.
To install @okta/okta-auth-js:
# Run this command in your project root folder.
# yarn
yarn add @okta/okta-auth-js
# npm
npm install --save @okta/okta-auth-js
If you are using the JS on a web page from the browser, you can copy the node_modules/@okta/okta-auth-js/dist
contents to publicly hosted directory, and include a reference to the okta-auth-js.min.js
file in a <script>
tag.
The built library bundle is also available on our global CDN. Include the following script in your HTML file to load before your application script:
<script src="https://global.oktacdn.com/okta-auth-js/5.2.2/okta-auth-js.min.js" type="text/javascript"></script>
⚠️ The version shown in this sample may be older than the current version. We recommend using the highest version available
Then you can create an instance of the OktaAuth
object, available globally.
const oktaAuth = new OktaAuth({
// config
})
However, if you're using a bundler like Webpack or Browserify, you can simply import the module or require using CommonJS.
// ES module
import { OktaAuth } from '@okta/okta-auth-js'
const authClient = new OktaAuth(/* configOptions */)
// CommonJS
var OktaAuth = require('@okta/okta-auth-js').OktaAuth;
var authClient = new OktaAuth(/* configOptions */);
For an overview of the client's features and authentication flows, check out our developer docs. There, you will learn how to use the Auth SDK on a simple static page to:
- Retrieve and store an OpenID Connect (OIDC) token
- Get an Okta session
⚠️ The developer docs may be written for an earlier version of this library. See Migrating from previous versions.
You can also browse the full API reference documentation.
⌛ Async methods return a promise which will resolve on success. The promise may reject if an error occurs.
var config = {
// Required config
issuer: 'https://{yourOktaDomain}/oauth2/default',
// Required for login flow using getWithRedirect()
clientId: 'GHtf9iJdr60A9IYrR0jw',
redirectUri: 'https://acme.com/oauth2/callback/home',
// Parse authorization code from hash fragment instead of search query
responseMode: 'fragment',
// Configure TokenManager to use sessionStorage instead of localStorage
tokenManager: {
storage: 'sessionStorage'
}
};
var authClient = new OktaAuth(config);
By default, creating a new instance of OktaAuth
will not create any asynchronous side-effects. However, certain features such as token auto renew, token auto remove and cross-tab synchronization require OktaAuth
to be running as a service. This means timeouts are set in the background which will continue working until the service is stopped. To start the OktaAuth
service, simply call the start
method. To terminate all background processes, call stop
.
var authClient = new OktaAuth(config);
authClient.start(); // start the service
authClient.stop(); // stop the service
Starting the service will also call authStateManager.updateAuthState.
Types are implicitly provided by this library through the types
entry in package.json
. Types can also be referenced explicitly by importing them.
import {
OktaAuth,
OktaAuthOptions,
TokenManager,
AccessToken,
IDToken,
UserClaims,
TokenParams
} from '@okta/okta-auth-js'
const config: OktaAuthOptions = {
issuer: 'https://{yourOktaDomain}'
}
const authClient: OktaAuth = new OktaAuth(config)
const tokenManager: TokenManager = authClient.tokenManager;
const accessToken: AccessToken = await tokenManager.get('accessToken') as AccessToken;
const idToken: IDToken = await tokenManager.get('idToken') as IDToken;
const userInfo: UserClaims = await authClient.getUserInfo(accessToken, idToken);
if (!userInfo) {
const tokenParams: TokenParams = {
scopes: ['openid', 'email', 'custom_scope'],
}
authClient.token.getWithRedirect(tokenParams);
}
Web and native clients can obtain tokens using the authorization_code
flow which uses a client secret stored in a secure location. SPA applications should use the PKCE
flow which does not use a client secret. To use the authorization_code
flow, set responseType
to "code"
and pkce
to false
:
var config = {
// Required config
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: 'GHtf9iJdr60A9IYrR0jw',
redirectUri: 'https://acme.com/oauth2/callback/home',
// Use authorization_code flow
responseType: 'code',
pkce: false
};
var authClient = new OktaAuth(config);
The PKCE OAuth flow will be used by default. This library includes built-in support for Node applications. PKCE is widely supported by most modern browsers when running on an HTTPS connection. PKCE requires that the browser implements crypto.subtle
(also known as webcrypto
). Most modern browsers provide this when running in a secure context (on an HTTPS connection). PKCE also requires the TextEncoder object. This is available on all major browsers except IE Edge. In this case, we recommend using a polyfill/shim such as text-encoding.
If the user's browser does not support PKCE, an exception will be thrown. You can test if a browser supports PKCE before construction with this static method:
OktaAuth.features.isPKCESupported()
Implicit OAuth flow is available as an option if PKCE flow cannot be supported in your deployment. It is widely supported by most browsers, and can work over an insecure HTTP connection. Note that implicit flow is less secure than PKCE flow, even over HTTPS, since raw tokens are exposed in the browser's history. For this reason, we highly recommending using the PKCE flow if possible.
Implicit flow can be enabled by setting the pkce
option to false
var config = {
pkce: false,
// other config
issuer: 'https://{yourOktaDomain}/oauth2/default',
};
var authClient = new OktaAuth(config);
! Routing is optional for the callback portion of the redirect strategy. Instead you can use popup or sign widget.
To sign a user in, your application must redirect the browser to the Okta-hosted sign-in page.
Note: Initial redirect to Okta-hosted sign-in page starts a transaction with a stateToken lifetime set to one hour.
After successful authentication, the browser is redirected back to your application along with information about the user. Depending on your preferences it is possible to use the following callback strategies.
- Create / configure your auth-js instance
- Before making any other calls with auth-js at the VERY BEGINNING of the app call token.isLoginRedirect - if this returns true, call parseFromUrl and save tokens in storage manager. It’s important that no other app logic runs until the async parseFromUrl / token manager logic is complete
- After continue normal app logic
According to the OAuth 2.0 spec the redirect URI "MUST NOT contain a fragment component": https://tools.ietf.org/html/rfc6749#section-3.1.2
So in case of using hash-based #
strategy and OAuth 2.0, the redirect URI can be defined only like a base url, without any specific route.
That's mean that hash-based router will receive the redirect callback on the main / default route. So we recommend to define the logic that will parse redirect url at the very beginning of your app. So the flow will be similar to Handling the callback without routing
Additionally if using hash routing, we recommend to use PKCE and responseMode query (which is the default for PKCE). Using implicit flow, with tokens in the hash could cause unpredictable results since hash routers like to rewrite the fragment.
- Right before redirect, save the route you are on (we recommend sessionStorage)
- Do the redirect to okta
- Redirect back to a dedicated route
- Call parseFromUrl(), retrieve tokens, add to
tokenManager
- Read saved route and redirect to it
Whether you are using this SDK to implement an OIDC flow or for communicating with the Authentication API, the only required configuration option is issuer
, which is the URL to an Okta Authorization Server
You may use the URL for your Okta organization as the issuer. This will apply a default authorization policy and issue tokens scoped at the organization level.
var config = {
issuer: 'https://{yourOktaDomain}'
};
var authClient = new OktaAuth(config);
Okta allows you to create multiple custom OAuth 2.0 authorization servers that you can use to protect your own resource servers. Within each authorization server you can define your own OAuth 2.0 scopes, claims, and access policies. Many organizations have a "default" authorization server.
var config = {
issuer: 'https://{yourOktaDomain}/oauth2/default'
};
var authClient = new OktaAuth(config);
You may also create and customize additional authorization servers.
var config = {
issuer: 'https://{yourOktaDomain}/oauth2/custom-auth-server-id'
};
var authClient = new OktaAuth(config);
These options can be included when instantiating Okta Auth JS (new OktaAuth(config)
).
⚠️ This option is required
The URL for your Okta organization or an Okta authentication server. About the issuer
Client Id pre-registered with Okta for the OIDC authentication flow. Creating your Okta application
The url that is redirected to when using token.getWithRedirect
. This must be listed in your Okta application's Login redirect URIs. If no redirectUri
is provided, defaults to the current origin (window.location.origin
). Configuring your Okta application
Specify the url where the browser should be redirected after signOut. This url must be listed in your Okta application's Logout redirect URIs. If not specified, your application's origin (window.location.origin
) will be used. Configuring your Okta application |
Specify what information to make available in the returned id_token
or access_token
. For OIDC, you must include openid
as one of the scopes. Defaults to ['openid', 'email']
. For a list of available scopes, see Scopes and Claims
A client-provided string that will be passed to the server endpoint and returned in the OAuth response. The value can be used to validate the OAuth response and prevent cross-site request forgery (CSRF). Defaults to a random string.
Default value is true
which enables the PKCE OAuth Flow. To use the Implicit Flow or Authorization Code Flow, set pkce
to false
.
When requesting tokens using token.getWithRedirect values will be returned as parameters appended to the redirectUri.
In most cases you will not need to set a value for responseMode
. Defaults are set according to the OpenID Connect 1.0 specification.
-
For PKCE OAuth Flow), the authorization code will be in search query of the URL. Clients using the PKCE flow can opt to instead receive the authorization code in the hash fragment by setting the responseMode option to "fragment".
-
For Implicit OAuth Flow), tokens will be in the hash fragment of the URL. This cannot be changed.
Specify the response type for OIDC authentication when using the Implicit OAuth Flow. The default value is ['token', 'id_token']
which will request both an access token and ID token. If pkce
is true
, both the access and ID token will be requested and this option will be ignored. For web/native applications using the authorization_code
flow, this value should be set to "code"
and pkce
should be set to false
.
Specify a custom authorizeUrl to perform the OIDC flow. Defaults to the issuer plus "/v1/authorize".
Specify a custom userinfoUrl. Defaults to the issuer plus "/v1/userinfo".
Specify a custom tokenUrl. Defaults to the issuer plus "/v1/token".
⚠️ This option should be used only for browser support and testing purposes.
ID token signatures are validated by default when token.getWithoutPrompt
, token.getWithPopup
, token.getWithRedirect
, and token.verify
are called. To disable ID token signature validation for these methods, set this value to true
.
Defaults to 300 (five minutes). This is the maximum difference allowed between a client's clock and Okta's, in seconds, when validating tokens. Setting this to 0 is not recommended, because it increases the likelihood that valid tokens will fail validation.
Callback function. When updateAuthState is called a new authState object is produced. Providing a transformAuthState
function allows you to modify or replace this object before it is stored and emitted. A common use case is to change the meaning of isAuthenticated. By default, updateAuthState
will set authState.isAuthenticated
to true if unexpired tokens are available from tokenManager. This logic could be customized to also require a valid Okta SSO session:
const config = {
// other config
transformAuthState: async (oktaAuth, authState) => {
if (!authState.isAuthenticated) {
return authState;
}
// extra requirement: user must have valid Okta SSO session
const user = await oktaAuth.token.getUserInfo();
authState.isAuthenticated = !!user; // convert to boolean
authState.users = user; // also store user object on authState
return authState;
}
};
const oktaAuth = new OktaAuth(config);
oktaAuth.authStateManager.subscribe(authState => {
// handle latest authState
});
oktaAuth.authStateManager.updateAuthState();
🔗 web browser only
Callback function. When sdk.handleLoginRedirect is called, by default it uses window.location.replace
to redirect back to the originalUri. This option overrides the default behavior.
const config = {
// other config
restoreOriginalUri: async (oktaAuth, originalUri) => {
// redirect with custom router
router.replace({
path: toRelativeUrl(originalUri, baseUrl)
});
}
};
const oktaAuth = new OktaAuth(config);
if (oktaAuth.isLoginRedirect()) {
oktaAuth.handleLoginRedirect();
}
Default to false
. It enables debugging logs when set to true
.
Enables interaction code flow for direct auth clients.
Used in authorization and interaction code flows by server-side web applications to obtain OAuth tokens. In a production application, this value should never be visible on the client side.
The http request implementation. By default, this is implemented using cross-fetch. To provide your own request library, implement the following interface:
- Must accept:
- method (http method)
- url (target url)
- args (object containing headers and data)
- Must return a Promise that resolves with a raw XMLHttpRequest response
var config = {
url: 'https://{yourOktaDomain}',
httpRequestClient: function(method, url, args) {
// args is in the form:
// {
// headers: {
// headerName: headerValue
// },
// data: postBodyData,
// withCredentials: true|false,
// }
return Promise.resolve(/* a raw XMLHttpRequest response */);
}
}
The storageManager
provides access to client storage for specific purposes. storageManager
configuration is divided into named sections. The default configuration is shown below:
var config = {
storageManager: {
token: {
storageTypes: [
'localStorage',
'sessionStorage',
'cookie'
],
useMultipleCookies: true // puts each token in its own cookie
},
cache: {
storageTypes: [
'localStorage',
'sessionStorage',
'cookie'
]
},
transaction: {
storageTypes: [
'sessionStorage',
'localStorage',
'cookie'
]
}
}
}
Important: If neither localStorage nor sessionStorage are available, the default storage provider may fall back to using cookie storage on some clients, . If your site will always be served over a HTTPS connection, you may want to forcibly enable "secure" cookies. This option will prevent cookies from being stored on an HTTP connection.
var config = {
cookies: {
secure: true
}
}
The following values for storageType
are recognized:
memory
: values are stored in a closure and will not survive a page reloadsessionStorage
: will only be available to the current browser tablocalStorage
: available to all browser tabscookie
: available to all browser tabs, and server-side code
Note: If the specified storageType
is not available, but matches an entry in storageTypes
, then default fallback logic will be applied. To disable this behavior, set storageTypes
to an empty array:
var config = {
storageManager: {
token: {
storageType: 'sessionStorage',
storageTypes: []
}
}
}
or set the storageTypes
property with only one entry:
var config = {
storageManager: {
token: {
storageTypes: ['sessionStorage']
}
}
}
If fallback logic is disabled, the storageManager may throw an exception if an instance of the given storageType
cannot be created.
A list of storageTypes, in order of preference. If a type is not available, the next type in the list will be tried.
This option allows you to pass a custom storage provider instance. If a storageProvider
is set, the storageType
will be ignored.
Important: A storage provider will receive sensitive data, such as the user's raw tokens, as a readable string. Any custom storage provider should take care to save this string in a secure location which is not accessible to unauthorized users.
A storageProvider
must provide a simple but specific API to access client storage. An example of a storageProvider
is the built-in localStorage. It has a method called getItem
that returns a string for a key and a method called setItem
which accepts a string and key.
A custom storage provider must implement two functions:
getItem(key)
setItem(key, value)
Optionally, a storage provider can also implement a removeItem
function. If removeItem
is not implemented, values will be cleared but keys will persist.
const myMemoryStore = {};
const storageProvider = {
getItem: function(key) {
// custom get
return myMemoryStore[key];
},
setItem: function(key, val) {
// custom set
myMemoryStore[key] = val;
},
// optional
removeItem: function(key) {
delete myMemoryStore[key];
}
}
var config = {
storageManager: {
token: {
storageProvider: storageProvider
}
}
}
If cookie
storage is specified, it is possible to specify whether or not a session cookie is used by the cookie storage. This will automatically be configured if sessionStorage
is specified and you fall back to cookie
storage. If sessionCookie is not specified it will create a cookie with an expiry date of 2200-01-01T00:00:00.000Z
var config = {
cookies: {
sessionCookie: true
}
}
⚙️ Requires a running service
By default, the tokenManager
will attempt to renew tokens before they expire. If you wish to manually control token renewal, set autoRenew
to false to disable this feature. You can listen to expired
events to know when the token has expired.
tokenManager: {
autoRenew: false
}
Renewing tokens slightly early helps ensure a stable user experience. By default, the expired
event will fire 30 seconds before actual expiration time. If autoRenew
is set to true, tokens will be renewed within 30 seconds of expiration. You can customize this value by setting the expireEarlySeconds
option. The value should be large enough to account for network latency and clock drift between the client and Okta's servers.
NOTE expireEarlySeconds
option is only allowed in the DEV environment (localhost). It will be reset to 30 seconds when running in environments other than DEV.
// Emit expired event 2 minutes before expiration
// Tokens accessed with tokenManager.get() will auto-renew within 2 minutes of expiration
tokenManager: {
expireEarlySeconds: 120
}
⚙️ Requires a running service
By default, the library will attempt to remove expired tokens during initialization when autoRenew
is off. If you wish to to disable auto removal of tokens, set autoRemove to false.
⚙️ Requires a running service
Automatically syncs tokens across browser tabs when token storage is localStorage
. To disable this behavior, set syncStorage
to false.
By default all tokens will be stored under the key okta-token-storage
. You may want to change this if you have multiple apps running on a single domain which share the same storage type. Giving each app a unique storage key will prevent them from reading or writing each other's token values.
Specify the storage type for tokens. This will override any value set for the token
section in the storageManager configuration. By default, localStorage will be used. This will fall back to sessionStorage or cookie if the previous type is not available. You may pass an object or a string. If passing an object, it should meet the requirements of a custom storage provider. Pass a string to specify one of the built-in storage types:
localStorage
(default)sessionStorage
cookie
memory
: a simple in-memory storage provider
var config = {
url: 'https://{yourOktaDomain}',
tokenManager: {
storage: 'sessionStorage'
}
};
var authClient = new OktaAuth(config);
A custom storage provider instance can also be passed here. (This will override any storageProvider
value set under the token
section of the storageManager configuration)
var myMemoryStore = {};
const storageProvider = {
getItem: function(key) {
// custom get
return myMemoryStore[key];
},
setItem: function(key, val) {
// custom set
myMemoryStore[key] = val;
},
// optional
removeItem: function(key) {
delete myMemoryStore[key];
}
}
const config = {
url: 'https://{yourOktaDomain}',
tokenManager: {
storage: storageProvider
}
};
const authClient = new OktaAuth(config);
const tokens = await authClient.token.getWithoutPrompt();
authClient.tokenManager.setTokens(tokens); // storageProvider.setItem
An object containing additional properties used when setting cookies
Defaults to true
, unless the application origin is http://localhost
, in which case it is forced to false
. If true
, the SDK will set the "Secure" option on all cookies. When this option is true
, an exception will be thrown if the application origin is not using the HTTPS protocol. Setting to false
will allow setting cookies on an HTTP origin, but is not recommended for production applications.
Defaults to none
if the secure
option is true
, or lax
if the secure
option is false. Allows fine-grained control over the same-site cookie setting. A value of none
allows embedding within an iframe. A value of lax
will avoid being blocked by user "3rd party" cookie settings. A value of strict
will block all cookies when redirecting from Okta and is not recommended.
- start
- stop
- signIn
- signInWithCredentials
- signInWithRedirect
- signOut
- closeSession
- revokeAccessToken
- revokeRefreshToken
- forgotPassword
- unlockAccount
- verifyRecoveryToken
- webfinger
- fingerprint
- isAuthenticated
- getUser
- getIdToken
- getAccessToken
- storeTokensFromRedirect
- setOriginalUri
- getOriginalUri
- removeOriginalUri
- isLoginRedirect
- handleLoginRedirect
- tx.resume
- tx.exists
- transaction.status
- session
- idx
- token
- tokenManager
- authStateManager
Starts the OktaAuth
service. See running as a service for more details.
Starts the OktaAuth
service. See running as a service for more details.
⚠️ Deprecated, this method will be removed in next major release, use signInWithCredentials instead.
⌛ async
The goal of this authentication flow is to set an Okta session cookie on the user's browser or retrieve an id_token
or access_token
. The flow is started using signInWithCredentials
.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g [email protected])password
- The password of the usersendFingerprint
- Enabling this will send aX-Device-Fingerprint
header. Defaults tofalse
. See Primary authentication with device fingerprint for more information on theX-Device-Fingerprint
header.
authClient.signInWithCredentials({
username: 'some-username',
password: 'some-password'
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.session.setCookieAndRedirect(transaction.sessionToken); // Sets a cookie on redirect
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.catch(function(err) {
console.error(err);
});
🔗 web browser only
Starts the full-page redirect to Okta with optional request parameters. In this flow, there is a originalUri parameter in options to track the route before the user signIn, and the addtional params are mapped to the Authorize options. You can use storeTokensFromRedirect to store tokens and getOriginalUri to clear the intermediate state (the originalUri) after successful authentication.
if (authClient.isLoginRedirect()) {
await authClient.handleLoginRedirect();
} else if (!await authClient.isAuthenticated()) {
// Start the browser based oidc flow, then parse tokens from the redirect callback url
authClient.signInWithRedirect();
} else {
// User is authenticated
}
⌛ async
Signs the user out of their current Okta session and clears all tokens stored locally in the TokenManager
. By default, the refresh token (if any) and access token are revoked so they can no longer be used. Some points to consider:
- Will redirect to an Okta-hosted page before returning to your app.
- If a
postLogoutRedirectUri
has not been specified or configured,window.location.origin
will be used as the return URI. This URI must be listed in the Okta application's Login redirect URIs. If the URI is unknown or invalid the redirect will end on a 400 error page from Okta. This error will be visible to the user and cannot be handled by the app. - Requires a valid ID token. If an ID token is not available,
signOut
will fallback to using the XHR-based closeSession method. This method may fail to sign the user out if 3rd-party cookies have been blocked by the browser. - For more information, see Logout in the OIDC API documentation.
signOut
takes the following options:
postLogoutRedirectUri
- Setting a value will override thepostLogoutRedirectUri
configured on the SDK.state
- An optional value, used along withpostLogoutRedirectUri
. If set, this value will be returned as a query parameter during the redirect to thepostLogoutRedirectUri
idToken
- Specifies the ID token object. By default,signOut
will look for a token object namedidToken
within theTokenManager
. If you have stored the id token object in a different location, you should retrieve it first and then pass it here.revokeAccessToken
- Iffalse
(default:true
) the access token will not be revoked. Use this option with care: not revoking tokens may pose a security risk if tokens have been leaked outside the application.revokeRefreshToken
- Iffalse
(default:true
) the refresh token will not be revoked. Use this option with care: not revoking tokens may pose a security risk if tokens have been leaked outside the application. Revoking a refresh token will revoke any access tokens minted by it, even ifrevokeAccessToken
isfalse
.accessToken
- Specifies the access token object. By default,signOut
will look for a token object namedaccessToken
within theTokenManager
. If you have stored the access token object in a different location, you should retrieve it first and then pass it here. This options is ignored if therevokeAccessToken
option isfalse
.
// Sign out using the default options
authClient.signOut()
// Override the post logout URI for this call
authClient.signOut({
postLogoutRedirectUri: `${window.location.origin}/logout/callback`
});
// In this case, the ID token is stored under the 'myIdToken' key
var idToken = await authClient.tokenManager.get('myIdToken');
authClient.signOut({
idToken: idToken
});
// In this case, the access token is stored under the 'myAccessToken' key
var accessToken = await authClient.tokenManager.get('myAccessToken');
authClient.signOut({
accessToken: accessToken
});
⚠️ This method requires access to third party cookies
⌛ async
Signs the user out of their current Okta session and clears all tokens stored locally in the TokenManager
. This method is an XHR-based alternative to signOut, which will redirect to Okta before returning to your application. Here are some points to consider when using this method:
- Executes in the background. The user will see not any change to
window.location
. - The method will fail to sign the user out if 3rd-party cookies are blocked by the browser.
- Does not revoke the access token. It is strongly recommended to call revokeAccessToken before calling this method
- It is recommended (but not required) for the app to call
window.location.reload()
after theXHR
method completes to ensure your app is properly re-initialized in an unauthenticated state. - For more information, see Close Current Session in the Session API documentation.
await authClient.revokeAccessToken(); // strongly recommended
authClient.closeSession()
.then(() => {
window.location.reload(); // optional
})
.catch(e => {
if (e.xhr && e.xhr.status === 429) {
// Too many requests
}
})
⌛ async
Revokes the access token for this application so it can no longer be used to authenticate API requests. The accessToken
parameter is optional. By default, revokeAccessToken
will look for a token object named accessToken
within the TokenManager
. If you have stored the access token object in a different location, you should retrieve it first and then pass it here. Returns a promise that resolves when the operation has completed. This method will succeed even if the access token has already been revoked or removed.
⌛ async
Revokes the refresh token (if any) for this application so it can no longer be used to mint new tokens. The refreshToken
parameter is optional. By default, revokeRefreshToken
will look for a token object named refreshToken
within the TokenManager
. If you have stored the refresh token object in a different location, you should retrieve it first and then pass it here. Returns a promise that resolves when the operation has completed. This method will succeed even if the refresh token has already been revoked or removed.
⌛ async
Starts a new password recovery transaction for a given user and issues a recovery token that can be used to reset a user’s password.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g [email protected])factorType
- Recovery factor to use for primary authentication. Supported options areSMS
,EMAIL
, orCALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transaction
authClient.forgotPassword({
username: '[email protected]',
factorType: 'SMS',
})
.then(function(transaction) {
return transaction.verify({
passCode: '123456' // The passCode from the SMS or CALL
});
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.session.setCookieAndRedirect(transaction.sessionToken);
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.catch(function(err) {
console.error(err);
});
⌛ async
Starts a new unlock recovery transaction for a given user and issues a recovery token that can be used to unlock a user’s account.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g [email protected])factorType
- Recovery factor to use for primary authentication. Supported options areSMS
,EMAIL
, orCALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transaction
authClient.unlockAccount({
username: '[email protected]',
factorType: 'SMS',
})
.then(function(transaction) {
return transaction.verify({
passCode: '123456' // The passCode from the SMS
});
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.session.setCookieAndRedirect(transaction.sessionToken);
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.catch(function(err) {
console.error(err);
});
⌛ async
Validates a recovery token that was distributed to the end-user to continue the recovery transaction.
recoveryToken
- Recovery token that was distributed to end-user via an out-of-band mechanism such as email
authClient.verifyRecoveryToken({
recoveryToken: '00xdqXOE5qDZX8-PBR1bYv8AESqIFinDy3yul01tyh'
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.session.setCookieAndRedirect(transaction.sessionToken);
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.catch(function(err) {
console.error(err);
});
⌛ async
Calls the Webfinger API and gets a response.
resource
- URI that identifies the entity whose information is sought, currently only acct scheme is supported (e.g acct:[email protected])rel
- Optional parameter to request only a subset of the information that would otherwise be returned without the "rel" parameter
authClient.webfinger({
resource: 'acct:[email protected]',
rel: 'okta:idp'
})
.then(function(res) {
// use the webfinger response to select an idp
})
.catch(function(err) {
console.error(err);
});
⌛ async
Creates a browser fingerprint. See Primary authentication with device fingerprint for more information.
timeout
- Time in ms until the operation times out. Defaults to15000
.
authClient.fingerprint()
.then(function(fingerprint) {
// Do something with the fingerprint
})
.catch(function(err) {
console.log(err);
})
⌛ async
Resolves with authState.isAuthenticated
from non-pending authState.
⌛ async
Alias method of token.getUserInfo.
Returns the id token string retrieved from authState if it exists.
Returns the access token string retrieved from authState if it exists.
⌛ async
Parses tokens from the redirect url and stores them.
Stores the current URL state before a redirect occurs. By default it stores window.location.href
.
Returns the stored URI string stored by setOriginal. By default it returns window.location.origin
.
Removes the stored URI string stored by setOriginal from storage.
🔗 web browser only
Check window.location
to verify if the app is in OAuth callback state or not. This function is synchronous and returns true
or false
.
if (authClient.isLoginRedirect()) {
// callback flow
await authClient.handleLoginRedirect();
} else {
// normal app flow
}
🔗 web browser only
Stores passed in tokens or tokens from redirect url into storage, then redirect users back to the originalUri. By default it calls window.location.replace
for the redirection. The default behavior can be overrided by providing options.restoreOriginalUri.
⌛ async
Resumes an in-progress transaction. This is useful if a user navigates away from the login page before authentication is complete.
var exists = authClient.tx.exists();
if (exists) {
authClient.tx.resume()
.then(function(transaction) {
console.log('current status:', transaction.status);
})
.catch(function(err) {
console.error(err);
});
}
Check for a transaction to be resumed. This is synchronous and returns true
or false
.
var exists = authClient.tx.exists();
if (exists) {
console.log('a session exists');
} else {
console.log('a session does not exist');
}
⌛ async
When Auth Client methods resolve, they return a transaction object that encapsulates the new state in the authentication flow. This transaction contains metadata about the current state, and methods that can be used to progress to the next state.
⌛ async Terminates the current auth flow.
transaction.cancel()
.then(function() {
// transaction canceled. You can now start another with authClient.signIn
});
Changes a user's password.
oldPassword
- User’s current password that is expirednewPassword
- New password for user
transaction.changePassword({
oldPassword: '0ldP4ssw0rd',
newPassword: 'N3wP4ssw0rd'
});
Reset a user's password.
newPassword
- New password for user
transaction.resetPassword({
newPassword: 'N3wP4ssw0rd'
});
Ignore the warning and continue.
transaction.skip();
The user account is locked; self-service unlock or admin unlock is required.
Example Response
{
status: 'LOCKED_OUT',
unlock: function(options) { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
Unlock the user account.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g [email protected])factorType
- Recovery factor to use for primary authentication. Supported options areSMS
,EMAIL
, orCALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transaction
transaction.unlock({
username: '[email protected]',
factorType: 'EMAIL'
});
The user’s password was successfully validated but is expired.
Example Response
{
status: 'PASSWORD_EXPIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
},
changePassword: function(options) { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
The user successfully answered their recovery question and can set a new password.
Example Response
{
status: 'PASSWORD_EXPIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
},
resetPassword: function(options) { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
The user’s password was successfully validated but is about to expire and should be changed.
Example Response
{
status: 'PASSWORD_WARN',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
},
policy: {
expiration:{
passwordExpireDays: 0
},
complexity: {
minLength: 8,
minLowerCase: 1,
minUpperCase: 1,
minNumber: 1,
minSymbol: 0,
excludeUsername: true
},
age:{
minAgeMinutes:0,
historyCount:0
}
},
changePassword: function(options) { /* returns another transaction */ },
skip: function() { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
The user has requested a recovery token to reset their password or unlock their account.
Example Response
{
status: 'RECOVERY',
expiresAt: '2014-11-02T23:39:03.319Z',
recoveryType: 'PASSWORD', // or 'UNLOCK'
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
},
recovery_question: {
question: "Who's a major player in the cowboy scene?"
}
},
answer: function(options) { /* returns another transaction */ },
recovery: function(options) { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
answer
- Answer to user’s recovery question
transaction.answer({
answer: 'My favorite recovery question answer'
});
recoveryToken
- Recovery token that was distributed to end-user via out-of-band mechanism such as email
transaction.recovery({
recoveryToken: '00xdqXOE5qDZX8-PBR1bYv8AESqIFinDy3yul01tyh'
});
The user must verify the factor-specific recovery challenge.
Example Response
{
status: 'RECOVERY_CHALLENGE',
expiresAt: '2014-11-02T23:39:03.319Z',
recoveryType: 'PASSWORD', // or 'UNLOCK',
factorType: 'EMAIL', // or 'SMS'
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
},
verify: function(options) { /* returns another transaction */ },
resend: function() { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
passCode
- OTP sent to device for verification
transaction.verify({
passCode: '615243'
});
Resend the recovery email or text.
transaction.resend();
When MFA is required, but a user isn’t enrolled in MFA, they must enroll in at least one factor.
Example Response
{
status: 'MFA_ENROLL',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
},
factors: [{
provider: 'OKTA',
factorType: 'question',
questions: function() { /* returns an array of possible questions */ },
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'OKTA',
factorType: 'sms',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'OKTA',
factorType: 'call',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'OKTA',
factorType: 'push',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'OKTA',
factorType: 'token:software:totp',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'GOOGLE',
factorType: 'token:software:totp',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'YUBICO',
factorType: 'token:hardware',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'RSA',
factorType: 'token',
enroll: function(options) { /* returns another transaction */ }
}, {
provider: 'SYMANTEC',
factorType: 'token',
enroll: function(options) { /* returns another transaction */ }
}],
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
To enroll in a factor, select one from the factors array, then use the following methods.
var factor = transaction.factors[/* index of the desired factor */];
List the available questions for the question factorType.
var questionFactor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'question';
});
questionFactor.questions()
.then(function(questions) {
// Display questions for the user to select from
});
The enroll options depend on the desired factor.
var questionFactor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'question';
});
questionFactor.enroll({
profile: {
question: 'disliked_food', // all questions available using questionFactor.questions()
answer: 'mayonnaise'
}
});
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'sms';
});
factor.enroll({
profile: {
phoneNumber: '+1-555-415-1337',
updatePhone: true
}
});
// The passCode sent to the phone is verified in MFA_ENROLL_ACTIVATE
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'call';
});
factor.enroll({
profile: {
phoneNumber: '+1-555-415-1337',
updatePhone: true
}
});
// The passCode from the call is verified in MFA_ENROLL_ACTIVATE
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'push';
});
factor.enroll();
// The phone will need to scan a QR Code in MFA_ENROLL_ACTIVATE
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'token:software:totp';
});
factor.enroll();
// The phone will need to scan a QR Code in MFA_ENROLL_ACTIVATE
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'GOOGLE' && factor.factorType === 'token:software:totp';
});
factor.enroll();
// The phone will need to scan a QR Code in MFA_ENROLL_ACTIVATE
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'YUBICO' && factor.factorType === 'token:hardware';
});
factor.enroll({
passCode: 'cccccceukngdfgkukfctkcvfidnetljjiknckkcjulji'
});
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'RSA' && factor.factorType === 'token';
});
factor.enroll({
passCode: '5275875498',
profile: {
credentialId: '[email protected]'
}
});
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'SYMANTEC' && factor.factorType === 'token';
});
factor.enroll({
passCode: '875498',
nextPassCode: '678195',
profile: {
credentialId: 'VSMT14393584'
}
});
The user must activate the factor to complete enrollment.
Example Response
{
status: 'MFA_ENROLL_ACTIVATE',
expiresAt: '2014-11-02T23:39:03.319Z',
factorResult: 'WAITING', // or 'TIMEOUT',
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
},
},
factor: {
id: 'opfh52xcuft3J4uZc0g3',
provider: 'OKTA',
factorType: 'push',
profile: {},
activation: {
expiresAt: '2015-04-01T15:57:32.000Z',
qrcode: {
href: 'https://acme.okta.com/api/v1/users/00ugti3kwafWJBRIY0g3/factors/opfh52xcuft3J4uZc0g3/qr/00fukNElRS_Tz6k-CFhg3pH4KO2dj2guhmaapXWbc4',
type: 'image/png'
}
}
},
resend: function() { /* returns another transaction */ },
activate: function(options) { /* returns another transaction */ },
poll: function() { /* returns another transaction */ },
prev: function() { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
Send another OTP if user doesn’t receive the original activation SMS OTP.
transaction.resend();
passCode
- OTP- sent to device for activation
transaction.activate({
passCode: '615243'
});
Poll until factorResult is not WAITING. Throws AuthPollStopError if prev, resend, or cancel is called.
transaction.poll();
End current factor enrollment and return to MFA_ENROLL
.
transaction.prev();
The user must provide additional verification with a previously enrolled factor.
Example Response
{
status: 'MFA_REQUIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
},
},
factors: [{
id: 'ufsigasO4dVUPM5O40g3',
provider: 'OKTA',
factorType: 'question',
profile: {
question: 'disliked_food',
questionText: 'What is the food you least liked as a child?'
},
verify: function(options) { /* returns another transaction */ }
}, {
id: 'opfhw7v2OnxKpftO40g3',
provider: 'OKTA',
factorType: 'push',
profile: {
credentialId: '[email protected]',
deviceType: 'SmartPhone_IPhone',
keys: [
{
kty: 'PKIX',
use: 'sig',
kid: 'default',
x5c: [
'MIIBIjANBgkqhkiG9w0BAQEFBAOCAQ8AMIIBCgKCAQEAs4LfXaaQW6uIpkjoiKn2g9B6nNQDraLyC3XgHP5cvX/qaqry43SwyqjbQtwRkScosDHl59r0DX1V/3xBtBYwdo8rAdX3I5h6z8lW12xGjOkmb20TuAiy8wSmzchdm52kWodUb7OkMk6CgRJRSDVbC97eNcfKk0wmpxnCJWhC+AiSzRVmgkpgp8NanuMcpI/X+W5qeqWO0w3DGzv43FkrYtfSkvpDdO4EvDL8bWX1Ad7mBoNVLWErcNf/uI+r/jFpKHgjvx3iqs2Q7vcfY706Py1m91vT0vs4SWXwzVV6pAVjD/kumL+nXfzfzAHw+A2vb6J2w06Rj71bqUkC2b8TpQIDAQAB'
]
}
],
name: 'Isaac\'s iPhone',
platform: 'IOS',
version: '8.1.3'
},
verify: function() { /* returns another transaction */ }
}, {
id: 'smsigwDlH85L9FyQK0g3',
provider: 'OKTA',
factorType: 'sms',
profile: {
phoneNumber: '+1 XXX-XXX-3355'
},
verify: function() { /* returns another transaction */ }
}, {
id: 'ostigevBq2NObXmTh0g3',
provider: 'OKTA',
factorType: 'token:software:totp',
profile: {
credentialId: '[email protected]'
},
verify: function() { /* returns another transaction */ }
}, {
id: 'uftigiEmYTPOmvqTS0g3',
provider: 'GOOGLE',
factorType: 'token:software:totp',
profile: {
credentialId: '[email protected]'
},
verify: function() { /* returns another transaction */ }
}],
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
To verify a factor, select one from the factors array, then use the following methods.
var factor = transaction.factors[/* index of the desired factor */];
var questionFactor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'question';
});
questionFactor.verify({
answer: 'mayonnaise'
});
autoPush
- Optional parameter to send a push notification immediately the next timeverify
is called on a push factor
var pushFactor = transaction.factors.find(function(factor) {
return factor.provider === 'OKTA' && factor.factorType === 'push';
});
pushFactor.verify({
autoPush: true
});
var factor = transaction.factors.find(function(factor) {
return factor.provider === 'YOUR_PROVIDER' && factor.factorType === 'yourFactorType';
});
factor.verify();
The user must verify the factor-specific challenge.
Example Response
{
status: 'MFA_CHALLENGE',
expiresAt: '2014-11-02T23:39:03.319Z',
factorResult: 'WAITING', // or CANCELLED, TIMEOUT, or ERROR
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: '[email protected]',
firstName: 'Isaac',
lastName: 'Brock',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
},
},
factor: {
id: 'smsigwDlH85L9FyQK0g3',
factorType: 'sms',
provider: 'OKTA',
profile: {
phoneNumber: '+1 XXX-XXX-6688'
}
},
verify: function(options) { /* returns another transaction */ },
poll: function() { /* returns another transaction */ },
prev: function() { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
passCode
- OTP sent to deviceautoPush
- Optional parameter to send a push notification immediately the next timeverify
is called on a push factor
transaction.verify({
passCode: '615243',
autoPush: true
});
autoPush
- Optional parameter to send a push notification immediately the next timeverify
is called on a push factor
Poll until factorResult is not WAITING. Throws AuthPollStopError if prev, resend, or cancel is called.
transaction.poll({
autoPush: true
});
End current factor verification and return to MFA_REQUIRED
.
transaction.prev();
The end of the authentication flow! This transaction contains a sessionToken you can exchange for an Okta cookie, an id_token
, or access_token
.
Example Response
{
expiresAt: '2015-06-08T23:34:34.000Z',
status: 'SUCCESS',
sessionToken: '00p8RhRDCh_8NxIin-wtF5M6ofFtRhfKWGBAbd2WmE',
user: {
id: '00uhm5QzwyZZxjrfp0g3',
profile: {
login: '[email protected]',
firstName: 'Test',
lastName: 'User',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
}
}
🔗 web browser only
⚠️ method requires access to [third party cookies]
(#third-party-cookies)
This allows you to create a session using a sessionToken.
sessionToken
- Ephemeral one-time token used to bootstrap an Okta session.redirectUri
- After setting a cookie, Okta redirects to the specified URI. The default is the current URI.
authClient.session.setCookieAndRedirect(transaction.sessionToken);
🔗 web browser only
⚠️ This method requires access to [third party cookies]
(#third-party-cookies) :hourglass: async
Returns a promise that resolves with true
if there is an existing Okta session, or false
if not.
authClient.session.exists()
.then(function(exists) {
if (exists) {
// logged in
} else {
// not logged in
}
});
🔗 web browser only
⚠️ This method requires access to [third party cookies]
(#third-party-cookies) :hourglass: async
Gets the active session.
authClient.session.get()
.then(function(session) {
// logged in
})
.catch(function(err) {
// not logged in
});
🔗 web browser only
⚠️ This method requires access to [third party cookies]
(#third-party-cookies) :hourglass: async
Refresh the current session by extending its lifetime. This can be used as a keep-alive operation.
authClient.session.refresh()
.then(function(session) {
// existing session is now refreshed
})
.catch(function(err) {
// there was a problem refreshing (the user may not have an existing session)
});
See detail in IDX README
The following configuration options can be included in token.getWithoutPrompt
, token.getWithPopup
, or token.getWithRedirect
. If an option with the same name is accepted in the constructor, passing the option to one of these methods will override the previously set value.
Options | Description |
---|---|
sessionToken |
Specify an Okta sessionToken to skip reauthentication when the user already authenticated using the Authentication Flow. |
responseType |
Specify the response type for OIDC authentication when using the Implicit OAuth Flow. The default value is ['token', 'id_token'] which will request both an access token and ID token. If pkce is true , both the access and ID token will be requested and this option will be ignored. |
scopes |
Specify what information to make available in the returned id_token or access_token . For OIDC, you must include openid as one of the scopes. Defaults to ['openid', 'email'] . For a list of available scopes, see Scopes and Claims. |
state |
A string that will be passed to /authorize endpoint and returned in the OAuth response. The value is used to validate the OAuth response and prevent cross-site request forgery (CSRF). The state value passed to getWithRedirect will be returned along with any requested tokens from parseFromUrl. Your app can use this string to perform additional validation and/or pass information from the login page. Defaults to a random string. |
nonce |
Specify a nonce that will be validated in an id_token . This is usually only provided during redirect flows to obtain an authorization code that will be exchanged for an id_token . Defaults to a random string. |
idp |
Identity provider to use if there is no Okta Session. |
idpScope |
A space delimited list of scopes to be provided to the Social Identity Provider when performing Social Login These scopes are used in addition to the scopes already configured on the Identity Provider. |
display |
The display parameter to be passed to the Social Identity Provider when performing Social Login. |
prompt |
Determines whether the Okta login will be displayed on failure. Use none to prevent this behavior. Valid values: none , consent , login , or consent login . See Parameter details for more information. |
maxAge |
Allowable elapsed time, in seconds, since the last time the end user was actively authenticated by Okta. |
loginHint |
A username to prepopulate if prompting for authentication. |
For more details, see Okta's Authorize Request API.
authClient.token.getWithoutPrompt({
sessionToken: '00p8RhRDCh_8NxIin-wtF5M6ofFtRhfKWGBAbd2WmE',
scopes: [
'openid',
'email',
'profile'
],
state: '8rFzn3MH5q',
nonce: '51GePTswrm',
// Use a custom IdP for social authentication
idp: '0oa62b57p7c8PaGpU0h7'
})
.then(function(res) {
var tokens = res.tokens;
// Do something with tokens, such as
authClient.tokenManager.setTokens(tokens);
})
.catch(function(err) {
// handle OAuthError or AuthSdkError
});
🔗 web browser only
⚠️ This method requires access to third party cookies
⌛ async
When you've obtained a sessionToken from the authorization flows, or a session already exists, you can obtain a token or tokens without prompting the user to log in.
options
- See Authorize options
authClient.token.getWithoutPrompt({
responseType: 'id_token', // or array of types
sessionToken: 'testSessionToken' // optional if the user has an existing Okta session
})
.then(function(res) {
var tokens = res.tokens;
// Do something with tokens, such as
authClient.tokenManager.setTokens(tokens);
})
.catch(function(err) {
// handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});
🔗 web browser only
⌛ async
Create token with a popup.
options
- See Authorize options
authClient.token.getWithPopup(options)
.then(function(res) {
var tokens = res.tokens;
// Do something with tokens, such as
authClient.tokenManager.setTokens(tokens);
})
.catch(function(err) {
// handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});
🔗 web browser only
⌛ async
Create token using a redirect. After a successful authentication, the browser will be redirected to the configured redirectUri. The authorization code, access, or ID Tokens will be available as parameters appended to this URL. Values will be returned in either the search query or hash fragment portion of the URL depending on the responseMode
options
- See Authorize options
authClient.token.getWithRedirect({
responseType: ['token', 'id_token'],
state: 'any-string-you-want-to-pass-to-callback' // will be URI encoded
})
.catch(function(err) {
// handle AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});
🔗 web browser only
⌛ async
Parses the authorization code, access, or ID Tokens from the URL after a successful authentication redirect. Values are parsed from either the search query or hash fragment portion of the URL depending on the responseMode.
If an authorization code is present, it will be exchanged for token(s) by posting to the tokenUrl
endpoint.
Note: Authorization code has a lifetime of one minute and can only be used once.
The ID token will be verified and validated before available for use.
In case access token is a part of OIDC flow response, its hash will be checked against ID token's at_hash
claim.
The state
string which was passed to getWithRedirect
will be also be available on the response.
authClient.token.parseFromUrl()
.then(function(res) {
var state = res.state; // passed to getWithRedirect(), can be any string
// manage token or tokens
var tokens = res.tokens;
// Do something with tokens, such as
authClient.tokenManager.setTokens(tokens);
})
.catch(function(err) {
// handle OAuthError
});
After reading values, this method will rewrite either the hash fragment or search query portion of the URL (depending on the responseMode) so that the code or tokens are no longer present or visible to the user. For this reason, it is recommended to use a dedicated route or path for the redirectUri so that this URL rewrite does not interfere with other URL parameters which may be used by your application. A complete login flow will usually save the current URL before calling getWithRedirect
and restore the URL after saving tokens from parseFromUrl
.
// On any page while unauthenticated. Begin login flow
// Save URL
sessionStorage.setItem('url', window.location.href);
// Redirect to Okta
authClient.token.getWithRedirect({
responseType: 'token'
});
// On callback (redirectUri) page
authClient.token.parseFromUrl()
.then(function(res) {
// Save token
authClient.tokenManager.setTokens(res.tokens);
// Read saved URL from storage
const url = sessionStorage.getItem('url');
sessionStorage.removeItem('url');
// Restore URL
window.location.assign(url);
})
.catch(function(err) {
// Handle OAuthError
});
Decode a raw ID Token
idTokenString
- an id_token JWT
const decodedToken = authClient.token.decode('YOUR_ID_TOKEN_JWT');
console.log(decodedToken.header, decodedToken.payload, decodedToken.signature);
⚠️ This method requires access to third party cookies ⌛ async
Returns a new token if the Okta session is still valid.
tokenToRenew
- an access token or ID token previously provided by Okta. note: this is not the raw JWT
// this token is provided by Okta via getWithoutPrompt, getWithPopup, and parseFromUrl
var tokenToRenew = {
idToken: 'YOUR_ID_TOKEN_JWT',
claims: { /* token claims */ },
expiresAt: 1449699930,
scopes: ['openid', 'email'],
authorizeUrl: 'https://{yourOktaDomain}/oauth2/v1/authorize',
issuer: 'https://{yourOktaDomain}',
clientId: 'NPSfOkH5eZrTy8PMDlvx'
};
authClient.token.renew(tokenToRenew)
.then(function(freshToken) {
// manage freshToken
})
.catch(function(err) {
// handle OAuthError
});
⌛ async
Retrieve the details about a user.
accessTokenObject
- (optional) an access token returned by this library. Note: this is not the raw access token.idTokenObject
- (optional) an ID token returned by this library. Note: this is not the raw ID token.
By default, if no parameters are passed, both the access token and ID token objects will be retrieved from the TokenManager. It is assumed that the access token is stored using the key "accessToken" and the ID token is stored under the key "idToken". If you have stored either token in a non-standard location, this logic can be skipped by passing the access and ID token objects directly.
// access and ID tokens are retrieved automatically from the TokenManager
authClient.token.getUserInfo()
.then(function(user) {
// user has details about the user
})
.catch(function(err) {
// handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});
// In this example, the access token is stored under the key 'myAccessToken', the ID token is stored under the key "myIdToken"
Promise.all([
authClient.tokenManager.get('myAccessToken'),
authClient.tokenManager.get('myIdToken')
])
.then(([accessTokenObject, idTokenObject]) => {
return authClient.token.getUserInfo(accessTokenObject, idTokenObject);
})
.then(function(user) {
// user has details about the user
})
.catch((err) => {
// handle AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});
⌛ async
Manually verify the validity of an ID token's claims and check the signature on browsers that support web cryptography.
Note: Token validation occurs automatically when tokens are returned via
getWithoutPrompt
,getWithPopup
, andgetWithRedirect
.
idTokenObject
- an ID token returned by this library. note: this is not the raw ID token JWTvalidationOptions
- Optional object to assert ID token claim values. Defaults to the configuration passed in during client instantiation.
var validationOptions = {
issuer: 'https://{yourOktaDomain}/oauth2/{authorizationServerId}'
}
authClient.token.verify(idTokenObject, validationOptions)
.then(function() {
// the idToken is valid
})
.catch(function(err) {
// handle AuthSdkError
});
🔗 web browser only
⚠️ Deprecated, this method will be removed in next major release, use sdk.isLoginRedirect instead.
Returns a TokenParams
object. If PKCE
is enabled, this object will contain values for codeVerifier
, codeChallenge
and codeChallengeMethod
.
Used internally to perform the final step of the PKCE
authorization code flow. Accepts a TokenParams
object which should contain a codeVerifier
and an authorizationCode
.
After receiving an access_token
or id_token
, add it to the tokenManager
to manage token expiration and renew operations. When a token is added to the tokenManager
, it is automatically renewed when it expires.
key
- Unique key to store the token in thetokenManager
. This is used later when you want to get, delete, or renew the token.token
- Token object that will be added
authClient.token.getWithPopup()
.then(function(res) {
authClient.tokenManager.add('idToken', res.tokens.idToken);
});
⌛ async
Get a token that you have previously added to the tokenManager
with the given key
. The token object will be returned if it exists in storage. Tokens will be removed from storage if they have expired and autoRenew
is false or if there was an error while renewing the token. The tokenManager
will emit a removed
event when tokens are removed.
key
- Key for the token you want to get
authClient.tokenManager.get('idToken')
.then(function(token) {
if (token && !authClient.tokenManager.hasExpired(token)) {
// Token is valid
console.log(token);
} else {
// Token has been removed due to expiration or error while renewing
}
})
.catch(function(err) {
// handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
console.error(err);
});
⌛ async
Returns storage key agnostic tokens set for available tokens from storage. It returns empty object ({}
) if no token is in storage.
authClient.tokenManager.getTokens()
.then(({ accessToken, idToken }) => {
// handle accessToken and idToken
});
Adds storage key agnostic tokens to storage. It uses default token storage keys (idToken
, accessToken
) in storage.
A synchronous method which returns true
if the token has expired. The tokenManager
will automatically remove expired tokens in the background. However, when the app first loads this background process may not have completed, so there is a chance that an expired token may exist in storage. This method can be called to avoid this potential race condition.
Remove a token from the tokenManager
with the given key
.
key
- Key for the token you want to remove
authClient.tokenManager.remove('idToken');
Remove all tokens from the tokenManager
.
authClient.tokenManager.clear();
⌛ async
Manually renew a token before it expires and update the stored value.
key
- Key for the token you want to renew
// Because the renew() method is async, you can wait for it to complete
// by using the returned Promise:
authClient.tokenManager.renew('idToken')
.then(function (newToken) {
console.log(newToken);
});
// Alternatively, you can subscribe to the 'renewed' event:
authClient.tokenManager.on('renewed', function (key, newToken, oldToken) {
console.log(newToken);
});
authClient.tokenManager.renew('idToken');
Subscribe to an event published by the tokenManager
.
event
- Event to subscribe to. Possible events are:added
- Fired when a new token has been added or updated (regardless of whether or not the token value was changed).expired
- Fired before a token is set to expire (usingexpireEarlySeconds
option, 30 seconds by default). IfautoRenew
option is set to true, a listener will be attached to this event and an attempt will be made to renew the token when the event fires.error
- Fired when a token renew attempt has failed. This is a permanent error, and the token will be removed from storage.renewed
- Fired when a token has been renewed by thetokenManager
, either via theautoRenew
process or as a result of callingtokenManager.renew
removed
- Fired when a token is removed from storage as a result of renew failure, or a call totokenManager.remove
. (This event will not fire fromtokenManager.clear
)
callback
- Function to call when the event is triggeredcontext
- Optional context to bind the callback to
// Triggered when a token has expired
authClient.tokenManager.on('expired', function (key, expiredToken) {
console.log('Token with key', key, ' has expired:');
console.log(expiredToken);
});
// Triggered when a token has been renewed
authClient.tokenManager.on('renewed', function (key, newToken, oldToken) {
console.log('Token with key', key, 'has been renewed');
console.log('Old token:', oldToken);
console.log('New token:', newToken);
});
// Triggered when an OAuthError is returned via the API (typically during token renew)
authClient.tokenManager.on('error', function (err) {
console.log('TokenManager error:', err);
// err.name
// err.message
// err.errorCode
// err.errorSummary
// err.tokenKey
// err.accessToken
});
Unsubscribe from tokenManager
events. If no callback is provided, unsubscribes all listeners from the event.
event
- Event to unsubscribe fromcallback
- Optional callback that was used to subscribe to the event
authClient.tokenManager.off('renewed');
authClient.tokenManager.off('renewed', myRenewedCallback);
AuthStateManager
evaluates and emits AuthState
based on the events from TokenManager
for downstream clients to consume.
The emitted AuthState
object includes:
isAuthenticated
: true if the user is considered authenticated. Normally this is true if both an idToken and an accessToken are present in the tokenManager, but this behavior can be overridden if you passed a transformAuthState callback in the configuration.accessToken
: the JWT accessToken for the currently authenticated user (if provided by the scopes).idToken
: the JWT idToken for the currently authenticated user (if provided by the scopes).error
: contains the error returned if an error occurs in theauthState
evaluation process.
Subscribes to authStateChange
event:
authClient.authStateManager.subscribe((authState) => {
// handle the latest evaluated authState, like integrate with client framework's state management store
});
Gets latest evaluated authState
from the authStateManager
. The authState
(a unique new object) is re-evaluated when authStateManager.updateAuthState()
is called. If updateAuthState
has not been called, or it has not finished calculating an initial state, getAuthState
will return null
.
Produces a unique authState
object and emits an authStateChange
event. The authState object contains tokens from the tokenManager
and a calculated isAuthenticated
value. By default, authState.isAuthenticated
will be true if both idToken
and accessToken
are present. This logic can be customized by defining a custom transformAuthState function.
The app needs call this method to call this method to initial the authState.
authClient.authStateManager.subscribe(authState => {
// handle emitted latest authState
});
if (!authClient.isLoginRedirect()) {
// Trigger an initial authState change event when the app startup
authClient.authStateManager.updateAuthState();
}
Subscribes a callback that will be called when the authStateChange
event happens.
Unsubscribes callback for authStateChange
event. It will unregister all handlers if no callback handler is provided.
You can use this library on the server side in your Node application or mobile client side in React Native environment. Some methods are only available in a web browser environment. These methods are marked in the README with this note:
🔗 web browser only
To include this library in your project, you can follow the instructions in the Getting started section.
You only need to set the issuer
for your Okta Domain:
var OktaAuth = require('@okta/okta-auth-js').OktaAuth;
var config = {
// The URL for your Okta organization
issuer: 'https://{yourOktaDomain}'
};
var authClient = new OktaAuth(config);
Since the Node library can be used only for the Authentication flow, it implements only a subset of okta-auth-js APIs:
The main difference is that the Node library does not have a session.setCookieAndRedirect
function, so you will have to redirect by yourself (for example using res.redirect('https://www.yoursuccesspage.com')
).
The SUCCESS
transaction will still include a sessionToken
which you can use with the session APIs: https://github.com/okta/okta-sdk-nodejs#sessions.
In most cases, you won't need to build the SDK from source. If you want to build it yourself, you'll need to follow these steps:
# Clone the repo
git clone https://github.com/okta/okta-auth-js.git
# Navigate into the new `okta-auth-js` filder
cd okta-auth-js
# Install Okta node dependencies and SDK will be built under `build`
yarn install
# navigate to the `build` folder
cd build
# create a link to the built package
yarn link
# navigate to your other project which has "@okta/okta-auth-js" as a dependency and create link
cd ../../other
yarn link @okta/okta-auth-js
Command | Description |
---|---|
yarn clean |
Removes installed dependencies and build outputs |
yarn install |
Install dependencies |
yarn build |
Build the SDK with a sourcemap |
yarn start |
Start internal test app |
yarn lint |
Run eslint linting |
yarn test:unit |
Run only unit tests |
yarn test:e2e |
Run only E2E (end-to-end) tests |
yarn test |
Run all tests |
Before running the E2E tests, you will need to setup a test environment. See test/e2e/README for more information.
We have implemented a small SPA app, located at ./test/app/
which is used internally as a test harness for the E2E tests. The app can be run manually using yarn start
. This will start a webpack dev server and open a new browser window at http://localhost:8080
. The app provides a high level of feedback and configurability which make it useful as a tool for troubleshooting and manual testing scenarios. See test/app/README for more information on the test app.
⚠️ Because this test app is set up to dynamically change configuration and leak internal information, users should not use source in the test app as the basis for their own applications. Instead, use the example usage outlined elsewhere in this README.
The CHANGELOG contains details for all changes and links to the original PR.
- Token auto renew requires running OktaAuth as a service. To start the service, call start().
start
will also call updateAuthState to set an initial AuthState - getAuthState will return
null
until an AuthState has been calculated. isPending
has been removed from AuthState.
- Now using named exports. You should change code like
// 3.x used default export
import OktaAuth from '@okta/okta-auth-js'
to
// 4.x uses named exports
import { OktaAuth } from '@okta/okta-auth-js'
If using CommonJS, change
// In 3.x module.exports was the OktaAuth object
const OktaAuth = require('@okta/okta-auth-js');
to
// In 4.x module.exports has a property named 'OktaAauth'
const OktaAuth = require('@okta/okta-auth-js').OktaAuth;
-
For Typescript users: definitions for types in this library are now included. If you were providing your own definitions for
@okta/okta-auth-js
you should remove these in favor of the types exported by this library. -
onSessionExpired
option has been removed. TokenManager events can be used to detect and handle token renewal errors.
-
Option
issuer
is required. Optionurl
has been deprecated and is no longer used. -
The object returned from
token.parseFromUrl()
is no longer an array containing token objects. It is now an object with a property calledtokens
which is a dictionary containing token objects. -
New behavior for signOut().
-
The default
responseMode
for PKCE flow is nowquery
.
We're happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.