Gathering detailed insights and metrics for @okta/okta-auth-js
Gathering detailed insights and metrics for @okta/okta-auth-js
Gathering detailed insights and metrics for @okta/okta-auth-js
Gathering detailed insights and metrics for @okta/okta-auth-js
The official js wrapper around Okta's auth API
npm install @okta/okta-auth-js
Typescript
Module System
Min. Node Version
Node Version
NPM Version
94.6
Supply Chain
98.2
Quality
82.6
Maintenance
100
Vulnerability
74.9
License
TypeScript (75.73%)
JavaScript (22.32%)
Shell (1.05%)
HTML (0.44%)
Gherkin (0.4%)
CSS (0.06%)
Total Downloads
80,742,883
Last Day
14,125
Last Week
561,679
Last Month
2,484,567
Last Year
25,156,675
NOASSERTION License
471 Stars
914 Commits
278 Forks
55 Watchers
893 Branches
78 Contributors
Updated on Jun 09, 2025
Minified
Minified + Gzipped
Latest Version
7.12.1
Package Id
@okta/okta-auth-js@7.12.1
Unpacked Size
18.02 MB
Size
3.86 MB
File Count
1,848
NPM Version
2.15.11
Node Version
4.8.1
Published on
Apr 08, 2025
Cumulative downloads
Total Downloads
Last Day
-13.3%
14,125
Compared to previous day
Last Week
-14%
561,679
Compared to previous week
Last Month
-0.1%
2,484,567
Compared to previous month
Last Year
29.3%
25,156,675
Compared to previous year
15
57
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.
:warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning:
:warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning::warning:
:heavy_check_mark: The current stable major version series is: 7.x
Version | Status |
---|---|
7.x | :heavy_check_mark: Stable |
6.x | :x: Retired |
5.x | :x: Retired |
4.x | :x: Retired |
3.x | :x: Retired |
2.x | :x: Retired |
1.x | :x: Retired |
0.x | :x: Retired |
The latest release can always be found on the releases page.
If you run into problems using the SDK, you can:
Users migrating from previous versions of this SDK should see Migrating Guide 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:
:warning: 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:
1import '@okta/okta-auth-js/polyfill';
or
1require('@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:
1<script src="https://global.oktacdn.com/okta-auth-js/7.5.1/okta-auth-js.polyfill.js" type="text/javascript" integrity="sha384-EBFsuVdi4TGp/DwS7b+t+wA8zmWK10omkX05ZjJWQhzWuW31t7FWEGOnHQeIr8+L" crossorigin="anonymous"></script>
:warning: 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:
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:
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:
To install @okta/okta-auth-js:
1# Run this command in your project root folder. 2# yarn 3yarn add @okta/okta-auth-js 4 5# npm 6npm 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:
1<script src="https://global.oktacdn.com/okta-auth-js/7.5.1/okta-auth-js.min.js" type="text/javascript" integrity="sha384-6epSwnIDkI5zFNEVNjEYy3A7aSZ+C7ehmEyG8zDJZfP9Bmnxc51TK8du+2me4pjb" crossorigin="anonymous"></script>
:warning: 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.
1const oktaAuth = new OktaAuth({ 2 // config 3})
However, if you're using a bundler like Webpack or Rollup you can simply import or require the module.
1// ES module 2import { OktaAuth } from '@okta/okta-auth-js' 3const authClient = new OktaAuth(/* configOptions */)
1// CommonJS 2var OktaAuth = require('@okta/okta-auth-js').OktaAuth; 3var 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:
:warning: 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.
:hourglass: Async methods return a promise which will resolve on success. The promise may reject if an error occurs.
1var config = { 2 issuer: 'https://{yourOktaDomain}/oauth2/default', 3 clientId: 'GHtf9iJdr60A9IYrR0jw', 4 redirectUri: 'https://acme.com/oauth2/callback/home', 5}; 6 7var 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 right after creation and before calling other methods like handleRedirect. To terminate all background processes, call stop
. See Service Configuration for more info.
1 var authClient = new OktaAuth(config); 2 await authClient.start(); // start the service 3 await authClient.stop(); // stop the service
Note: Starting the service will also call authStateManager.updateAuthState.
Type definitions are provided implicitly through the types
entry in package.json
. Types can also be referenced explicitly by importing them.
1import { 2 OktaAuth, 3 OktaAuthOptions, 4 TokenManagerInterface, 5 AccessToken, 6 IDToken, 7 UserClaims, 8 TokenParams 9} from '@okta/okta-auth-js'; 10 11const config: OktaAuthOptions = { 12 issuer: 'https://{yourOktaDomain}' 13}; 14 15const authClient: OktaAuth = new OktaAuth(config); 16const tokenManager: TokenManagerInterface = authClient.tokenManager; 17const accessToken: AccessToken = await tokenManager.get('accessToken') as AccessToken; 18const idToken: IDToken = await tokenManager.get('idToken') as IDToken; 19const userInfo: UserClaims = await authClient.token.getUserInfo(accessToken, idToken); 20 21if (!userInfo) { 22 const tokenParams: TokenParams = { 23 scopes: ['openid', 'email', 'custom_scope'], 24 }; 25 authClient.token.getWithRedirect(tokenParams); 26}
Typescript versions prior to 3.6 have no type definitions for WebAuthn.
Support for WebAuthn in IDX API was introduced in @okta/okta-auth-js@6.1.0
.
To solve this issue please install package @types/webappsec-credential-management
version ^0.5.1
.
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
:
1var config = { 2 // Required config 3 issuer: 'https://{yourOktaDomain}/oauth2/default', 4 clientId: 'GHtf9iJdr60A9IYrR0jw', 5 redirectUri: 'https://acme.com/oauth2/callback/home', 6 7 // Use authorization_code flow 8 responseType: 'code', 9 pkce: false 10}; 11 12var authClient = new OktaAuth(config);
The PKCE OAuth flow will be used by default. This library supports PKCE for both browser and NodeJS 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 11 and Edge < v79. To add support, 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()
:warning: We strongly discourage using the implicit flow. Use PKCE and/or client credentials if possible.
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
1 2var config = { 3 pkce: false, 4 5 // other config 6 issuer: 'https://{yourOktaDomain}/oauth2/default', 7}; 8 9var authClient = new OktaAuth(config);
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.
Most applications will handle an OAuth callback using a special route/page, separate from the signin page. However some SPA applications have no routing logic and will want to handle everything in a single page.
1 2async function main() { 3 // create OktaAuth instance 4 var config = { 5 issuer: 'https://{yourOktaDomain}/oauth2/default', 6 clientId: 'GHtf9iJdr60A9IYrR0jw', 7 redirectUri: 'https://acme.com/oauth2/callback/home', 8 }; 9 authClient = new OktaAuth(config); 10 11 // Subscribe to authState change event. 12 authClient.authStateManager.subscribe(function(authState) { 13 // Logic based on authState is done here. 14 if (!authState.isAuthenticated) { 15 // render unathenticated view 16 return; 17 } 18 19 // Render authenticated view 20 }); 21 22 // Handle callback 23 if (authClient.token.isLoginRedirect()) { 24 const { tokens } = await authClient.token.parseFromUrl(); // remember to "await" this async call 25 authClient.tokenManager.setTokens(tokens); 26 } 27 28 // normal app startup 29 authClient.start(); // will update auth state and call event listeners 30}
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 When using a hash/fragment routing strategy and OAuth 2.0, the redirect callback will be the main / default route. The redirect callback flow will be very similar to handling the callback without routing. We recommend defining the logic that will parse redirect url at the very beginning of your app, before any other authorization checks.
Additionally, if using hash routing, we recommend using PKCE and responseMode "query" (this is the default for PKCE). With implicit flow, tokens in the hash could cause unpredictable results since hash routers may rewrite the fragment.
TokenManager
: tokenManager.setTokensReference: DPoP (Demonstrating Proof-of-Possession) - RFC9449
DPoP
must be enabled in your Okta application (Guide: Configure DPoP)https
is required. A secure context is required for WebCrypto.subtle
IndexedDB
(MDN, caniuse)1const config = { 2 // other configurations 3 pkce: true, // required 4 dpop: true, 5 dpopOptions: { 6 // set to `true` to skip the validation to check the resulting token response includes `token_type: DPoP` 7 allowBearerTokens: false // defaults to `false`, tokens are validated to include `token_type: DPoP` 8 } 9}; 10 11const authClient = new OktaAuth(config);
Reference: The DPoP Authentication Scheme (RFC9449)
GET /protectedresource HTTP/1.1
Host: resource.example.org
Authorization: DPoP Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxU
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsIm...
1async function dpopAuthenticatedFetch (url, options) { 2 const { method } = options; 3 const dpop = await authClient.getDPoPAuthorizationHeaders({ url, method }); 4 // dpop = { Authorization: "DPoP token****", Dpop: "proof****" } 5 const headers = new Headers({...options.headers, ...dpop}); 6 return fetch(url, {...options, headers }); 7}
use_dpop_nonce
Reference: Resource Server-Provided Nonce (RFC9449)
Resource servers can also choose to provide a nonce value to be included in DPoP proofs sent to them. They provide the nonce using the DPoP-Nonce header in the same way that authorization servers do...
HTTP/1.1 401 Unauthorized
WWW-Authenticate: DPoP error="use_dpop_nonce", \
error_description="Resource server requires nonce in DPoP proof"
DPoP-Nonce: eyJ7S_zG.eyJH0-Z.HX4w-7v
1async function dpopAuthenticatedFetch (url, options) { 2 // ...previous example... 3 const resp = await fetch(url, {...options, headers }); 4 // resp = HTTP/1.1 401 Unauthorized... 5 6 if (!resp.ok) { 7 const nonce = authClient.parseUseDPoPNonceError(resp.headers); 8 if (nonce) { 9 const retryDpop = await authClient.getDPoPAuthorizationHeaders({ url, method, nonce }); 10 const retryHeaders = new Headers({...options.headers, ...retryDpop}); 11 return fetch(url, {...options, headers: retryHeaders }); 12 } 13 } 14 15 return resp; 16}
DPoP requires certain browser features. A user using a browser without the required features will unable to complete a request for tokens. It's recommended to verify browser support during application bootstrapping.
1// App.tsx 2useEffect(() => { 3 if (!authClient.features.isDPoPSupported()) { 4 // user will be unable to request tokens 5 navigate('/unsupported-error-page'); 6 } 7}, []);
DPoP requires the generation of a CryptoKeyPair
which needs to be persisted in storage. Methods like signOut()
or revokeAccessToken()
will clear the key pair, however users don't always explicitly logout. It's therefore good practice to clear storage before login to flush any orphaned key pairs generated from previously requested tokens.
1async function login (options) { 2 await authClient.clearDPoPStorage(); // clear possibly orphaned key pairs 3 4 return authClient.signInWithRedirect(options); 5}
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.
1var config = { 2 issuer: 'https://{yourOktaDomain}' 3}; 4 5var 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.
1var config = { 2 issuer: 'https://{yourOktaDomain}/oauth2/default' 3}; 4 5var authClient = new OktaAuth(config);
You may also create and customize additional authorization servers.
1 2var config = { 3 issuer: 'https://{yourOktaDomain}/oauth2/custom-auth-server-id' 4}; 5 6var authClient = new OktaAuth(config);
These options can be included when instantiating Okta Auth JS (new OktaAuth(config)
).
issuer
:warning: This option is required
The URL for your Okta organization or an Okta authentication server. About the issuer
clientId
Client Id pre-registered with Okta for the OIDC authentication flow. Creating your Okta application
redirectUri
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
postLogoutRedirectUri
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 |
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 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.
pkce
Default value is true
which enables the PKCE OAuth Flow. To use the Implicit Flow or Authorization Code Flow, set pkce
to false
.
dpop
Default value is false
. Set to true
to enable DPoP
(Demonstrating Proof-of-Possession (RFC9449))
See Guide: Enabling DPoP
dpopOptions
Default value:
1dpopOptions: { 2 allowBearerTokens: false 3}
See Guide: Enabling DPoP
dpopOptions.allowBearerTokens
When false
, dpop-enabled token requests are validated to contain token_type: DPoP
and will throw otherwise. Set to true
to skip this validation and allow Bearer
tokens as a possible token_type
. This can be useful during a migration, to avoid needing to update a web application simutaneously with Okta Org configurations. Defaults 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.
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. For web/native applications using the authorization_code
flow, this value should be set to "code"
and pkce
should be set to false
.
authorizeUrl
Specify a custom authorizeUrl to perform the OIDC flow. Defaults to the issuer plus "/v1/authorize".
userinfoUrl
Specify a custom userinfoUrl. Defaults to the issuer plus "/v1/userinfo".
tokenUrl
Specify a custom tokenUrl. Defaults to the issuer plus "/v1/token".
ignoreSignature
:warning: 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
.
maxClockSkew
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.
ignoreLifetime
:warning: This option disables token lifetime validation, which can introduce security vulnerability issues. This option should be used for testing purpose. Please handle the error in your own app for production environment.
Token lifetimes are validated using the maxClockSkew. To override this and disable token lifetime validation, set this value to true
.
transformAuthState
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:
1const config = { 2 // other config 3 transformAuthState: async (oktaAuth, authState) => { 4 if (!authState.isAuthenticated) { 5 return authState; 6 } 7 // extra requirement: user must have valid Okta SSO session 8 const user = await oktaAuth.token.getUserInfo(); 9 authState.isAuthenticated = !!user; // convert to boolean 10 authState.users = user; // also store user object on authState 11 return authState; 12 } 13}; 14 15const oktaAuth = new OktaAuth(config); 16oktaAuth.authStateManager.subscribe(authState => { 17 // handle latest authState 18}); 19oktaAuth.authStateManager.updateAuthState();
restoreOriginalUri
:link: web browser only
Callback function. When sdk.handleRedirect is called, by default it uses window.location.replace
to redirect back to the originalUri. This option overrides the default behavior.
1const config = { 2 // other config 3 restoreOriginalUri: async (oktaAuth, originalUri) => { 4 // redirect with custom router 5 router.replace({ 6 path: toRelativeUrl(originalUri, baseUrl) 7 }); 8 } 9}; 10 11const oktaAuth = new OktaAuth(config); 12if (oktaAuth.isLoginRedirect()) { 13 try { 14 await oktaAuth.handleRedirect(); 15 } catch (e) { 16 // log or display error details 17 } 18}
devMode
Default to false
. It enables debugging logs when set to true
.
clientSecret
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.
setLocation
Used in authorization and interaction code flows by server-side web applications to customize the redirect process.
httpRequestClient
The http request implementation. By default, this is implemented using cross-fetch. To provide your own request library, implement the following interface:
1var config = { 2 url: 'https://{yourOktaDomain}', 3 httpRequestClient: function(method, url, args) { 4 // args is in the form: 5 // { 6 // headers: { 7 // headerName: headerValue 8 // }, 9 // data: postBodyData, 10 // withCredentials: true|false, 11 // } 12 return Promise.resolve(/* a raw XMLHttpRequest response */); 13 } 14}
storageManager
The storageManager
provides access to client storage for specific purposes. storageManager
configuration is divided into named sections. The default configuration is shown below:
1 2var config = { 3 storageManager: { 4 token: { 5 storageTypes: [ 6 'localStorage', 7 'sessionStorage', 8 'cookie' 9 ], 10 }, 11 cache: { 12 storageTypes: [ 13 'localStorage', 14 'sessionStorage', 15 'cookie' 16 ] 17 }, 18 transaction: { 19 storageTypes: [ 20 'sessionStorage', 21 'localStorage', 22 'cookie' 23 ] 24 } 25 } 26}
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.
1var config = { 2 cookies: { 3 secure: true 4 } 5}
storageType
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 codeNote: 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:
1var config = { 2 storageManager: { 3 token: { 4 storageType: 'sessionStorage', 5 storageTypes: [] 6 } 7 } 8}
or set the storageTypes
property with only one entry:
1var config = { 2 storageManager: { 3 token: { 4 storageTypes: ['sessionStorage'] 5 } 6 } 7}
If fallback logic is disabled, the storageManager may throw an exception if an instance of the given storageType
cannot be created.
storageTypes
A list of storageTypes, in order of preference. If a type is not available, the next type in the list will be tried.
storageProvider
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.
1const myMemoryStore = {}; 2const storageProvider = { 3 getItem: function(key) { 4 // custom get 5 return myMemoryStore[key]; 6 }, 7 setItem: function(key, val) { 8 // custom set 9 myMemoryStore[key] = val; 10 }, 11 // optional 12 removeItem: function(key) { 13 delete myMemoryStore[key]; 14 } 15} 16 17var config = { 18 storageManager: { 19 token: { 20 storageProvider: storageProvider 21 } 22 } 23}
tokenManager
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
1var config = { 2 cookies: { 3 sessionCookie: true 4 } 5}
autoRenew
:warning: Moved to TokenService. For backwards compatibility will set
services.tokenService.autoRenew
expireEarlySeconds
:warning: DEV ONLY
To facilitate a more stable user experience, tokens are considered expired 30 seconds before actual expiration time. 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.
1// Emit expired event 2 minutes before expiration 2// Tokens accessed with tokenManager.get() will auto-renew within 2 minutes of expiration 3tokenManager: { 4 expireEarlySeconds: 120 5}
autoRemove
:warning: Moved to TokenService. For backwards compatibility will set
services.tokenService.autoRenew
syncStorage
:warning: Moved to SyncStorageService. For backwards compatibility will set
services.syncStorageService.enable
storageKey
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.
storage
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 provider1 2var config = { 3 url: 'https://{yourOktaDomain}', 4 tokenManager: { 5 storage: 'sessionStorage' 6 } 7}; 8 9var 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)
1var myMemoryStore = {}; 2const storageProvider = { 3 getItem: function(key) { 4 // custom get 5 return myMemoryStore[key]; 6 }, 7 setItem: function(key, val) { 8 // custom set 9 myMemoryStore[key] = val; 10 }, 11 // optional 12 removeItem: function(key) { 13 delete myMemoryStore[key]; 14 } 15} 16 17const config = { 18 url: 'https://{yourOktaDomain}', 19 tokenManager: { 20 storage: storageProvider 21 } 22}; 23 24const authClient = new OktaAuth(config); 25const { tokens } = await authClient.token.getWithoutPrompt(); 26authClient.tokenManager.setTokens(tokens); // storageProvider.setItem 27
cookies
An object containing additional properties used when setting cookies
secure
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.
sameSite
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.
clearPendingRemoveTokens
Defaults to true
, set this option to false if you want to opt-out of the default clearing pendingRemove tokens behaviour when tokenManager.start()
is called.
services
:gear: Requires a running service The following configurations require
OktaAuth
to be running as a service. See running service for more info.
Default configuration:
1services: { 2 autoRenew: true, 3 autoRemove: true, 4 syncStorage: true, 5 renewOnTabActivation: true, 6 tabInactivityDuration: 1800 // seconds 7}
autoRenew
When true
, the library 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.
NOTE tokens are considered
expired
slightly before their actual expiration time. For more info, see expireEarlySeconds.
In version 6.X
, the autoRenew
configuration was set in config.tokenManager
. To maintain backwards compatibility, this configuration is still respected but with a slight caveat. tokenManager.autoRenew
configures 2 token auto renew strategies, active
and passive
.
active
- Network requests are made in the background in an attempt to refresh tokens before they are truly expired to maintain a seamless UX.
:warning: this can cause an unintended side effect where the session never expires because it is constantly being refreshed (extended) before the actual expiration time
passive
- Token refresh attempts are only made when oktaAuth.isAuthenticated
is called and the current tokens are determined to be expired.When tokenManager.autoRenew
is true
both renew strategies are enabled. To disable the active
strategy, set tokenManager.autoRenew
to true
and services.autoRenew
to false
. To disable both renew strategies set either tokenManager.autoRenew
or services.autoRenew
to false
autoRemove
By default, the library will attempt to remove expired tokens when autoRemove
is true
. If you wish to disable auto removal of tokens, set autoRemove
to false
.
syncStorage
Automatically syncs tokens across browser tabs when it's supported in browser (browser supports native broadcastchannel API, IndexDB or localStorage). To disable this behavior, set syncStorage
to false.
This is accomplished by selecting a single tab to handle the network requests to refresh the tokens and broadcasting to the other tabs. This is done to avoid all tabs sending refresh requests simultaneously, which can cause rate limiting/throttling issues.
renewOnTabActivation
NOTE: This service requires
autoRenew: true
When enabled ({ autoRenew: true, renewOnTabActivation: true }
), this service binds a handler to the Page Visibility API which attempts a token renew (if needed) when the tab becomes active after a (configurable) inactivity period
tabInactivityDuration
The amount of time, in seconds, a tab needs to be inactive for the RenewOnTabActivation
service to attempt a token renew. Defaults to 1800
(30 mins)
start()
:hourglass: async
Starts the OktaAuth
service. See running as a service for more details.
stop()
:hourglass: async
Stops the OktaAuth
service. See running as a service for more details.
signIn(options)
:warning: Deprecated, this method will be removed in next major release, use signInWithCredentials instead.
signInWithCredentials(options)
See authn API.
signInWithRedirect(options)
:link: web browser only
:hourglass: async
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.
1if (authClient.isLoginRedirect()) { 2 try { 3 await authClient.handleRedirect(); 4 } catch (e) { 5 // log or display error details 6 } 7} else if (!await authClient.isAuthenticated()) { 8 // Start the browser based oidc flow, then parse tokens from the redirect callback url 9 authClient.signInWithRedirect(); 10} else { 11 // User is authenticated 12}
signOut()
:hourglass: async :link: web browser only
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:
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.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.signOut()
returns a promise that resolves with the result of closeSession (true
if an existing Okta session have been closed or false
if a session does not exist or has already been closed). Otherwise a promise resolves with true
.signOut
takes the following options:
postLogoutRedirectUri
- Setting a value will override the postLogoutRedirectUri
configured on the SDK. This will default to window.location.origin
if no value is provided. To prevent this explicitly pass null
to leverage the default behavior of /logout
. If signOut
falls back to closeSession
window.location.origin
will still be used as the default value, even if null
is passed.state
- An optional value, used along with postLogoutRedirectUri
. If set, this value will be returned as a query parameter during the redirect to the postLogoutRedirectUri
idToken
- Specifies the ID token object. By default, signOut
will look for a token object named idToken
within the TokenManager
. If you have stored the id token object in a different location, you should retrieve it first and then pass it here.clearTokensBeforeRedirect
- If true
(default: false
) local tokens will be removed before the logout redirect happens. Otherwise a flag (pendingRemove
) will be added to each local token instead of clearing them immediately. Calling oktaAuth.start()
after logout redirect will clear local tokens if flags are found. Use this option with care: removing local tokens before fully terminating the Okta SSO session can result in logging back in again when using @okta/okta-react
's SecureRoute
component.revokeAccessToken
- If false
(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
- If false
(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 if revokeAccessToken
is false
.accessToken
- Specifies the access token object. By default, signOut
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. This options is ignored if the revokeAccessToken
option is false
.1// Sign out using the default options 2authClient.signOut()
1// Override the post logout URI for this call 2authClient.signOut({ 3 postLogoutRedirectUri: `${window.location.origin}/logout/callback` 4});
1// In this case, the ID token is stored under the 'myIdToken' key 2var idToken = await authClient.tokenManager.get('myIdToken'); 3authClient.signOut({ 4 idToken: idToken 5});
1// In this case, the access token is stored under the 'myAccessToken' key 2var accessToken = await authClient.tokenManager.get('myAccessToken'); 3authClient.signOut({ 4 accessToken: accessToken 5});
closeSession()
:warning: This method requires access to third party cookies
:hourglass: async
Signs the user out of their current Okta session and clears all tokens stored locally in the TokenManager
. Returns a promise that resolves with true
if an existing Okta session have been closed, or false
if a session does not exist or has already been closed. 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:
window.location
.window.location.reload()
after the XHR
method completes to ensure your app is properly re-initialized in an unauthenticated state.1await authClient.revokeAccessToken(); // strongly recommended 2authClient.closeSession() 3 .then((sessionClosed) => { 4 if (sessionClosed) { 5 window.location.reload(); // optional 6 } else { 7 // Session does not exist or has already been closed 8 } 9 }) 10 .catch(e => { 11 if (e.xhr && e.xhr.status === 429) { 12 // Too many requests 13 } 14 })
revokeAccessToken(accessToken)
:hourglass: 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.
revokeRefreshToken(refreshToken)
:hourglass: 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.
forgotPassword(options)
See authn API.
unlockAccount(options)
See authn API.
verifyRecoveryToken(options)
See authn API.
webfinger(options)
:hourglass: 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:dade.murphy@example.com)rel
- Optional parameter to request only a subset of the information that would otherwise be returned without the "rel" parameter1authClient.webfinger({ 2 resource: 'acct:john.joe@example.com', 3 rel: 'okta:idp' 4}) 5.then(function(res) { 6 // use the webfinger response to select an idp 7}) 8.catch(function(err) { 9 console.error(err); 10});
fingerprint(options)
:hourglass: async
Creates a browser fingerprint. See Primary authentication with device fingerprint for more information.
timeout
- Time in ms until the operation times out. Defaults to 15000
.1authClient.fingerprint() 2.then(function(fingerprint) { 3 // Do something with the fingerprint 4}) 5.catch(function(err) { 6 console.log(err); 7})
isAuthenticated(options?)
:hourglass: async
Resolves with authState.isAuthenticated
from non-pending authState.
options
expiredTokenBehavior
: 'renew'
(default) | 'remove'
| 'none'
'renew'
- attempt to renew token before Promise
resolves'remove'
- removes token'none'
- neither renews or removes expired tokenNOTE:
tokenManager.autoRenew
andtokenManager.autoRemove
determine the default value forexpiredTokenBehavior
getUser()
:hourglass: async
Alias method of token.getUserInfo.
getIdToken()
Returns the id token string retrieved from authState if it exists.
getAccessToken()
Returns the access token string retrieved from authState if it exists.
getOrRenewAccessToken()
Returns the access token string if it exists. Returns null
if the access token doesn't exist or a renewal cannot be completed
storeTokensFromRedirect()
:hourglass: async
Parses tokens from the redirect url and stores them.
setOriginalUri(uri?)
Stores the current URL state before a redirect occurs.
getOriginalUri(state?)
Returns the stored URI string stored by setOriginal. An OAuth state
parameter is optional. If no value is passed for state
, the URI is retrieved from isolated session storage and will work in a single browser. If a valid OAuth state
is passed this method can return the URI stored from another browser tab.
removeOriginalUri()
Removes the stored URI string stored by setOriginal from storage.
isLoginRedirect()
:link: 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
.
1if (authClient.isLoginRedirect()) { 2 // callback flow 3 try { 4 await authClient.handleRedirect(); 5 } catch (e) { 6 // log or display error details 7 } 8} else { 9 // normal app flow 10}
handleLoginRedirect(tokens?, originalUri?)
:link: web browser only
:hourglass: async
:warning: Deprecated, this method could be removed in next major release, use sdk.handleRedirect instead.
Stores passed in tokens or tokens from redirect url into storage, then redirect users back to the originalUri. When using PKCE
authorization code flow, this method also exchanges authorization code for tokens. By default it calls window.location.replace
for the redirection. The default behavior can be overrided by providing options.restoreOriginalUri. By default, originalUri will be retrieved from storage, but this can be overridden by passing a value fro originalUri
to this function in the 2nd parameter.
Note:
handleLoginRedirect
throwsOAuthError
orAuthSdkError
in case there are errors during token retrieval.
handleRedirect(originalUri?)
:link: web browser only
:hourglass: async
Handle a redirect to the configured redirectUri that happens on the end of login flow, enroll authenticator flow or on an error.
Stores tokens from redirect url into storage (for login flow), then redirect users back to the originalUri. When using PKCE
authorization code flow, this method also exchanges authorization code for tokens. By default it calls window.location.replace
for the redirection. The default behavior can be overrided by providing options.restoreOriginalUri. By default, originalUri will be retrieved from storage, but this can be overridden by specifying originalUri
in the first parameter to this function.
Note:
handleRedirect
throwsOAuthError
orAuthSdkError
in case there are errors during token retrieval or authenticator enrollment.
handleIDPPopupRedirect(url?)
:link: web browser only
:hourglass: async
Used in conjunction with token.getWithIDPPopup
. Handles the redirect from the Authorization Server back to the web application. This method relays the resulting OAuth2 response from the popup window to the main window.
setHeaders()
Can set (or unset) request headers after construction.
1const authClient = new OktaAuth({ 2 issuer: 'https://{yourOktaDomain}', 3 4 // headers can be set during construction 5 headers: { 6 foo: 'bar' 7 } 8}); 9 10// Headers can be set (or modified) after construction 11authClient.setHeaders({ 12 foo: 'baz' 13}); 14 15// Headers can be removed 16authClient.setHeaders({ 17 foo: undefined 18})
tx.resume()
See authn API.
tx.exists()
See authn API.
transaction.status
See authn API.
getDPoPAuthorizationHeaders(params)
:link: web browser only
:hourglass: async
Requires dpop set to true
. Returns Authorization
and Dpop
header values to build a DPoP protected-request.
Params: url
and (http) method
are required.
accessToken
is optional, but will be read from tokenStorage
if not providednonce
is optional, may be provided via use_dpop_nonce
pattern from Resource Server (more info)parseUseDPoPNonceError(headers)
:link: web browser only
Utility to extract and parse the WWW-Authenticate
and DPoP-Nonce
headers from a network response from a DPoP-protected request. Should the response be in the following format, the nonce
value will be returned. Otherwise returns null
HTTP/1.1 401 Unauthorized
WWW-Authenticate: DPoP error="use_dpop_nonce", \
error_description="Resource server requires nonce in DPoP proof"
DPoP-Nonce: eyJ7S_zG.eyJH0-Z.HX4w-7v
clearDPoPStorage(clearAll=false)
:link: web browser only
:hourglass: async
Clears storage location of CryptoKeyPair
s generated and used by DPoP. Pass true
to remove all key pairs as it's possible for orphaned key pairs to exist. If clearAll
is false
, the key pair bound to the current accessToken
in tokenStorage will be removed.
It's recommended to call this function during user login. See Example
session
session.setCookieAndRedirect(sessionToken, redirectUri)
See authn API.
session.exists()
:link: web browser only
:warning: This method requires access to third party cookies
:hourglass: async
Returns a promise that reso
No vulnerabilities found.
Reason
security policy file detected
Details
Reason
no binaries found in the repo
Reason
11 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 9
Reason
license file detected
Details
Reason
Found 20/30 approved changesets -- score normalized to 6
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
53 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More