Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
@okta/okta-auth-js
Advanced tools
@okta/okta-auth-js is a JavaScript library that provides a set of tools for integrating Okta's authentication and authorization services into your web applications. It allows you to handle user authentication, manage tokens, and interact with Okta's APIs.
User Authentication
This feature allows you to authenticate users by their username and password. The code sample demonstrates how to sign in a user and handle the authentication transaction.
const OktaAuth = require('@okta/okta-auth-js');
const authClient = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: 'http://localhost:8080/login/callback'
});
async function signIn(username, password) {
try {
const transaction = await authClient.signIn({ username, password });
if (transaction.status === 'SUCCESS') {
authClient.token.getWithRedirect({
sessionToken: transaction.sessionToken
});
} else {
throw new Error('We cannot handle the ' + transaction.status + ' status');
}
} catch (err) {
console.error(err);
}
}
Token Management
This feature allows you to manage tokens, including obtaining tokens without prompting the user. The code sample demonstrates how to get an ID token using the OktaAuth client.
const OktaAuth = require('@okta/okta-auth-js');
const authClient = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: 'http://localhost:8080/login/callback'
});
async function getToken() {
try {
const token = await authClient.token.getWithoutPrompt({
responseType: 'id_token',
scopes: ['openid', 'profile', 'email']
});
console.log(token);
} catch (err) {
console.error(err);
}
}
Session Management
This feature allows you to manage user sessions. The code sample demonstrates how to check the current session using the OktaAuth client.
const OktaAuth = require('@okta/okta-auth-js');
const authClient = new OktaAuth({
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: '{clientId}',
redirectUri: 'http://localhost:8080/login/callback'
});
async function checkSession() {
try {
const session = await authClient.session.get();
console.log(session);
} catch (err) {
console.error(err);
}
}
Auth0.js is a JavaScript library for integrating Auth0's authentication and authorization services into your web applications. It provides similar functionalities to @okta/okta-auth-js, such as user authentication, token management, and session handling. However, it is designed to work with Auth0's platform instead of Okta.
Firebase Authentication is a service provided by Google Firebase that offers backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports various authentication methods, including email/password, phone number, and social providers like Google, Facebook, and Twitter. While it provides similar functionalities to @okta/okta-auth-js, it is part of the larger Firebase ecosystem.
Passport is a popular authentication middleware for Node.js. It provides a comprehensive set of strategies for authenticating with different services, including local username/password, OAuth, and OpenID Connect. While it offers similar functionalities to @okta/okta-auth-js, it is more flexible and can be used with various authentication providers.
The Okta Auth JavaScript SDK builds on top of our Authentication API and 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.
:heavy_check_mark: The current stable major version series is: 2.x
Version | Status |
---|---|
2.x | :heavy_check_mark: Stable |
1.x | :warning: Retiring on 2019-05-31 |
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:
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:
Using our npm module is a good choice if:
To install @okta/okta-auth-js:
# Run this command in your project root folder.
# yarn
yarn add --save @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.
However, if you're using a bundler like Webpack or Browserify, you can simply import the module using CommonJS.
var OktaAuth = require('@okta/okta-auth-js');
var authClient = new OktaAuth(/* configOptions */);
If you're using a bundler like webpack or browserify, we have implementations for jquery and reqwest included. To use them, import the SDK like this:
// reqwest
var OktaAuth = require('@okta/okta-auth-js/reqwest');
// jquery
var OktaAuth = require('@okta/okta-auth-js/jquery');
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:
You can also browse the full API reference documentation.
If you are using this SDK to implement an OIDC flow, the only required configuration option is issuer
:
var config = {
issuer: 'https://{yourOktaDomain}/oauth2/default'
};
var authClient = new OktaAuth(config);
If you’re using this SDK only for communicating with the Authentication API, you instead need to set the url
for your Okta Domain:
var config = {
// The URL for your Okta organization
url: 'https://{yourOktaDomain}'
};
var authClient = new OktaAuth(config);
These configuration options can be included when instantiating Okta Auth JS (new OktaAuth(config)
) or in token.getWithoutPrompt
, token.getWithPopup
, or token.getWithRedirect
(unless noted otherwise). If included in both, the value passed in the method takes priority.
tokenManager
Important: This configuration option can be included only when instantiating Okta Auth JS.
Specify the type of storage for tokens. Defaults to localStorage and will fall back to sessionStorage, and/or cookie if the previous type is not available.
var config = {
url: 'https://{yourOktaDomain}',
tokenManager: {
storage: 'sessionStorage'
}
};
var authClient = new OktaAuth(config);
Even if you have specified localStorage
or sessionStorage
in your config, the TokenManager
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 enable "secure" cookies. This option will prevent cookies from being stored on an HTTP connection.
tokenManager: {
secure: true
}
By default, the tokenManager
will attempt to renew expired tokens. When an expired token is requested by the tokenManager.get()
method, a renewal request is executed to update the token. 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, if accessed with tokenManager.get()
. You can customize this value by setting the expireEarlySeconds
option. The value should be large enough to account for network latency between the client and Okta's servers.
// Emit expired event 2 minutes before expiration
// Tokens accessed with tokenManager.get() will auto-renew within 2 minutes of expiration
tokenManager: {
expireEarlySeconds: 120
}
Option | Description |
---|---|
issuer | Specify a custom issuer to perform the OIDC flow. Defaults to the base url parameter if not provided. |
clientId | Client Id pre-registered with Okta for the OIDC authentication flow. |
redirectUri | The url that is redirected to when using token.getWithRedirect . This must be pre-registered as part of client registration. If no redirectUri is provided, defaults to the current origin. |
pkce | If set to true, the authorization flow will automatically use PKCE. The authorize request will use response_type=code , and grant_type=authorization_code will be used on the token request. All these details are handled for you, including the creation and verification of code verifiers. |
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 | 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 . |
This option should be used only for browser support and testing purposes. | |
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. |
var config = {
url: 'https://{yourOktaDomain}',
// Optional config
issuer: 'https://{yourOktaDomain}/oauth2/default',
clientId: 'GHtf9iJdr60A9IYrR0jw',
redirectUri: 'https://acme.com/oauth2/callback/home',
// Override the default authorize and userinfo URLs
authorizeUrl: 'https://{yourOktaDomain}/oauth2/default/v1/authorize',
userinfoUrl: 'https://{yourOktaDomain}/oauth2/default/v1/userinfo',
// TokenManager config
tokenManager: {
storage: 'sessionStorage'
}
};
var authClient = new OktaAuth(config);
By default the implicit
OAuth flow will be used. It is widely supported by most browsers. PKCE is a newer flow which is more secure, but does require certain capabilities from the browser.
To use PKCE flow, set pkce
to true
in your config.
var config = {
pkce: true,
// other config
issuer: 'https://{yourOktaDomain}/oauth2/default',
};
var authClient = new OktaAuth(config);
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()
httpRequestClient
The http request implementation. By default, this is implemented using reqwest for browser and cross-fetch for server. To provide your own request library, implement the following interface:
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 */);
}
}
ajaxRequest
:warning: This parameter has been deprecated, please use httpRequestClient instead.
The ajax request implementation. By default, this is implemented using reqwest. To provide your own request library, implement the following interface:
var config = {
url: 'https://{yourOktaDomain}',
ajaxRequest: function(method, url, args) {
// args is in the form:
// {
// headers: {
// headerName: headerValue
// },
// data: postBodyData
// }
return Promise.resolve(/* a raw XMLHttpRequest response */);
}
}
signIn(options)
The goal of an 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 signIn
.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g dade.murphy@example.com)password
- The password of the usersendFingerprint
- Enabling this will send a X-Device-Fingerprint
header. Defaults to false
authClient.signIn({
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';
}
})
.fail(function(err) {
console.error(err);
});
signOut()
Signs the user out of their current Okta session.
authClient.signOut()
.then(function() {
console.log('successfully logged out');
})
.fail(function(err) {
console.error(err);
});
forgotPassword(options)
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 dade.murphy@example.com)factorType
- Recovery factor to use for primary authentication. Supported options are SMS
, EMAIL
, or CALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transactionauthClient.forgotPassword({
username: 'dade.murphy@example.com',
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';
}
})
.fail(function(err) {
console.error(err);
});
unlockAccount(options)
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 dade.murphy@example.com)factorType
- Recovery factor to use for primary authentication. Supported options are SMS
, EMAIL
, or CALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transactionauthClient.unlockAccount({
username: 'dade.murphy@example.com',
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';
}
})
.fail(function(err) {
console.error(err);
});
verifyRecoveryToken(options)
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 emailauthClient.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';
}
})
.fail(function(err) {
console.error(err);
});
webfinger(options)
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" parameterauthClient.webfinger({
resource: 'acct:john.joe@example.com',
rel: 'okta:idp'
})
.then(function(res) {
// use the webfinger response to select an idp
})
.fail(function(err) {
console.error(err);
});
fingerprint(options)
Creates a browser fingerprint.
timeout
- Time in ms until the operation times out. Defaults to 15000
.authClient.fingerprint()
.then(function(fingerprint) {
// Do something with the fingerprint
})
.fail(function(err) {
console.log(err);
})
tx.resume()
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);
})
.fail(function(err) {
console.error(err);
});
}
tx.exists()
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');
}
transaction.status
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.
cancel()
Terminates the current auth flow.
transaction.cancel()
.then(function() {
// transaction canceled. You can now start another with authClient.signIn
});
changePassword(options)
Changes a user's password.
oldPassword
- User’s current password that is expirednewPassword
- New password for usertransaction.changePassword({
oldPassword: '0ldP4ssw0rd',
newPassword: 'N3wP4ssw0rd'
});
resetPassword(options)
Reset a user's password.
newPassword
- New password for usertransaction.resetPassword({
newPassword: 'N3wP4ssw0rd'
});
skip()
Ignore the warning and continue.
transaction.skip();
The user account is locked; self-service unlock or admin unlock is required.
{
status: 'LOCKED_OUT',
unlock: function(options) { /* returns another transaction */ },
cancel: function() { /* terminates the auth flow */ },
data: { /* the parsed json response */ }
}
unlock(options)
Unlock the user account.
username
- User’s non-qualified short-name (e.g. dade.murphy) or unique fully-qualified login (e.g dade.murphy@example.com)factorType
- Recovery factor to use for primary authentication. Supported options are SMS
, EMAIL
, or CALL
relayState
- Optional state value that is persisted for the lifetime of the recovery transactiontransaction.unlock({
username: 'dade.murphy@example.com',
factorType: 'EMAIL'
});
The user’s password was successfully validated but is expired.
{
status: 'PASSWORD_EXPIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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.
{
status: 'PASSWORD_EXPIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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.
{
status: 'PASSWORD_WARN',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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.
{
status: 'RECOVERY',
expiresAt: '2014-11-02T23:39:03.319Z',
recoveryType: 'PASSWORD', // or 'UNLOCK'
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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(options)
answer
- Answer to user’s recovery questiontransaction.answer({
answer: 'My favorite recovery question answer'
});
recovery(options)
recoveryToken
- Recovery token that was distributed to end-user via out-of-band mechanism such as emailtransaction.recovery({
recoveryToken: '00xdqXOE5qDZX8-PBR1bYv8AESqIFinDy3yul01tyh'
});
The user must verify the factor-specific recovery challenge.
{
status: 'RECOVERY_CHALLENGE',
expiresAt: '2014-11-02T23:39:03.319Z',
recoveryType: 'PASSWORD', // or 'UNLOCK',
factorType: 'EMAIL', // or 'SMS'
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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 */ }
}
verify(options)
passCode
- OTP sent to device for verificationtransaction.verify({
passCode: '615243'
});
resend()
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.
{
status: 'MFA_ENROLL',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ub0oNGTSWTBKOLGLNR',
profile: {
login: 'isaac@example.org',
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 */];
questions()
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
});
enroll(options)
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: 'dade.murphy@example.com'
}
});
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.
{
status: 'MFA_ENROLL_ACTIVATE',
expiresAt: '2014-11-02T23:39:03.319Z',
factorResult: 'WAITING', // or 'TIMEOUT',
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: 'isaac@example.org',
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 */ }
}
resend()
Send another OTP if user doesn’t receive the original activation SMS OTP.
transaction.resend();
activate(options)
passCode
- OTP- sent to device for activationtransaction.activate({
passCode: '615243'
});
poll()
Poll until factorResult is not WAITING. Throws AuthPollStopError if prev, resend, or cancel is called.
transaction.poll();
prev()
End current factor enrollment and return to MFA_ENROLL
.
transaction.prev();
The user must provide additional verification with a previously enrolled factor.
{
status: 'MFA_REQUIRED',
expiresAt: '2014-11-02T23:39:03.319Z',
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: 'isaac@example.org',
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: 'isaac@example.org',
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: 'isaac@example.org'
},
verify: function() { /* returns another transaction */ }
}, {
id: 'uftigiEmYTPOmvqTS0g3',
provider: 'GOOGLE',
factorType: 'token:software:totp',
profile: {
credentialId: 'isaac@example.org'
},
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 time verify
is called on a push factorvar 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.
{
status: 'MFA_CHALLENGE',
expiresAt: '2014-11-02T23:39:03.319Z',
factorResult: 'WAITING', // or CANCELLED, TIMEOUT, or ERROR
user: {
id: '00ugti3kwafWJBRIY0g3',
profile: {
login: 'isaac@example.org',
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 */ }
}
verify(options)
passCode
- OTP sent to deviceautoPush
- Optional parameter to send a push notification immediately the next time verify
is called on a push factortransaction.verify({
passCode: '615243',
autoPush: true
});
poll(options)
autoPush
- Optional parameter to send a push notification immediately the next time verify
is called on a push factorPoll until factorResult is not WAITING. Throws AuthPollStopError if prev, resend, or cancel is called.
transaction.poll({
autoPush: true
});
prev()
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
.
{
expiresAt: '2015-06-08T23:34:34.000Z',
status: 'SUCCESS',
sessionToken: '00p8RhRDCh_8NxIin-wtF5M6ofFtRhfKWGBAbd2WmE',
user: {
id: '00uhm5QzwyZZxjrfp0g3',
profile: {
login: 'exampleUser@example.com',
firstName: 'Test',
lastName: 'User',
locale: 'en_US',
timeZone: 'America/Los_Angeles'
}
}
}
session
session.setCookieAndRedirect(sessionToken, redirectUri)
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);
session.exists()
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
}
});
session.get()
Gets the active session.
authClient.session.get()
.then(function(session) {
// logged in
})
.catch(function(err) {
// not logged in
});
session.refresh()
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)
});
token
The following configuration options can only be included in token.getWithoutPrompt
, token.getWithPopup
, or token.getWithRedirect
.
Options | Description |
---|---|
sessionToken | Specify an Okta sessionToken to skip reauthentication when the user already authenticated using the Authentication Flow. |
responseMode | Specify how the authorization response should be returned. You will generally not need to set this unless you want to override the default values for token.getWithRedirect . See Parameter Details for a list of available modes. |
responseType | Specify the response type for OIDC authentication. The default value is id_token . If pkce is true , this option will be ingored. |
Use an array if specifying multiple response types - in this case, the response will contain both an ID Token and an Access Token. responseType: ['id_token', 'token'] | |
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 | Specify a state that will be validated in an OAuth response. This is usually only provided during redirect flows to obtain an authorization code. 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. |
For a list of all available parameters that can be passed to the /authorize
endpoint, 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(tokenOrTokens) {
// manage token or tokens
})
.catch(function(err) {
// handle OAuthError
});
token.getWithoutPrompt(oauthOptions)
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.
oauthOptions
- See Extended OpenID Connect optionsauthClient.token.getWithoutPrompt({
responseType: 'id_token', // or array of types
sessionToken: 'testSessionToken' // optional if the user has an existing Okta session
})
.then(function(tokenOrTokens) {
// manage token or tokens
})
.catch(function(err) {
// handle OAuthError
});
token.getWithPopup(oauthOptions)
Create token with a popup.
oauthOptions
- See Extended OpenID Connect optionsauthClient.token.getWithPopup(oauthOptions)
.then(function(tokenOrTokens) {
// manage token or tokens
})
.catch(function(err) {
// handle OAuthError
});
token.getWithRedirect(options)
Create token using a redirect.
oauthOptions
- See Extended OpenID Connect optionsauthClient.token.getWithRedirect(oauthOptions);
token.parseFromUrl(options)
Parses the authorization code, access, or ID Tokens from the URL after a successful authentication redirect.
If an authorization code is present, it will be exchanged for token(s) by posting to the tokenUrl
endpoint.
The ID token will be verified and validated before available for use.
authClient.token.parseFromUrl()
.then(function(tokenOrTokens) {
// manage token or tokens
})
.catch(function(err) {
// handle OAuthError
});
token.decode(idTokenString)
Decode a raw ID Token
idTokenString
- an id_token JWTauthClient.token.decode('YOUR_ID_TOKEN_JWT');
token.renew(tokenToRenew)
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
});
token.getUserInfo(accessTokenObject)
Retrieve the details about a user.
accessTokenObject
- an access token returned by this library. note: this is not the raw access tokenauthClient.token.getUserInfo(accessTokenObject)
.then(function(user) {
// user has details about the user
});
token.verify(idTokenObject)
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
});
tokenManager
tokenManager.add(key, token)
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 the tokenManager
. This is used later when you want to get, delete, or renew the token.token
- Token object that will be addedauthClient.token.getWithPopup()
.then(function(idToken) {
authClient.tokenManager.add('idToken', idToken);
});
tokenManager.get(key)
Get a token that you have previously added to the tokenManager
with the given key
. The token object will be returned if it has not expired.
key
- Key for the token you want to getauthClient.tokenManager.get('idToken')
.then(function(token) {
if (token) {
// Token is valid
console.log(token);
} else {
// Token has expired
}
})
.catch(function(err) {
// OAuth Error
console.error(err);
});
tokenManager.remove(key)
Remove a token from the tokenManager
with the given key
.
key
- Key for the token you want to removeauthClient.tokenManager.remove('idToken');
tokenManager.clear()
Remove all tokens from the tokenManager
.
authClient.tokenManager.clear();
tokenManager.renew(key)
Manually renew a token before it expires.
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');
tokenManager.on(event, callback[, context])
Subscribe to an event published by the tokenManager
.
event
- Event to subscribe to. Possible events are expired
, error
, and renewed
.callback
- Function to call when the event is triggeredcontext
- Optional context to bind the callback to// Triggered when the token has expired
authClient.tokenManager.on('expired', function (key, expiredToken) {
console.log('Token with key', key, ' has expired:');
console.log(expiredToken);
});
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
authClient.tokenManager.on('error', function (err) {
console.log('TokenManager error:', err.message);
// err.name
// err.message
// err.errorCode
// err.errorSummary
});
tokenManager.off(event[, callback])
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 eventauthClient.tokenManager.off('renewed');
authClient.tokenManager.off('renewed', myRenewedCallback);
You can use this library on server side in your Node application as an Authentication SDK. It can only be used in this way for communicating with the Authentication API, not to implement an OIDC flow.
To include this library in your project, you can follow the instructions in the Getting started section.
You only need to set the url
for your Okta Domain:
var OktaAuth = require('@okta/okta-auth-js');
var config = {
// The URL for your Okta organization
url: '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 `dist`
yarn install
Command | Description |
---|---|
yarn build | Build the SDK with a sourcemap |
yarn test | Run unit tests |
yarn lint | Run eslint linting |
yarn start | Start internal test app |
Implements a simple SPA application to demonstrate functionality and provide for manual testing. See here for more information.
We're happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.
FAQs
The Okta Auth SDK
The npm package @okta/okta-auth-js receives a total of 96,392 weekly downloads. As such, @okta/okta-auth-js popularity was classified as popular.
We found that @okta/okta-auth-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.