Auth0.js is a client-side JavaScript library for Auth0. It supports both hosted login and embedded login use cases.The full API documentation for the library is here.
Embedded login for web applications uses cross-origin authentication unless you configure a custom domain for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
The example directory of the auth0.js library is a ready-to-go app that can help you to quickly and easily try out auth0.js. In order to run it, follow these quick steps:
Download dependencies by running npm install from the root of this project
Finally, execute npm start from the root of this project, and then browse to your app running on the node server, presumably at http://localhost:3000/example.
Configure your Auth0 application for embedded login
When implementing embedded login, the library will use cross-origin calls inside hidden iframes to perform authentication. To make sure this can be done securely, Auth0 needs to know the domains where you will be hosting your applications.Add the domain to the Allowed Web Origins field. You can find this field in the Application Settings area of your Dashboard.
There are two required parameters that must be passed in the options object when instantiating webAuth and more that are optional.
Parameter
Required
Description
domain
required
(String) Your Auth0 account domain (ex. myaccount.auth0.com)
clientID
required
(String) Your Auth0 client ID
redirectUri
optional*
(String) The default redirectUri used. Defaults to an empty string (none). If you do not provide a global redirectUri value here, you will need to provide a redirectUri value for each method you use.
scope
optional
(String) The default used by the application. Using scopes can allow you to return specific claims for specific fields in your request. You should read our documentation on scopes for further details.
audience
optional
(String) The default audience to be used for requesting API access.
responseType
optional*
(String) The default responseType used. It can be any space separated list of the values code, token, id_token. It defaults to 'token', unless a redirectUri is provided, then it defaults to 'code'. If you do not provide a global responseType value, you will need to provide a responseType value for each method you use.
responseMode
optional
(String) This option is omitted by default. Can be set to 'form_post' in order to send the token or code to the 'redirectUri' via POST. Supported values are query, fragment and form_post.
leeway
optional
(Integer) A value in seconds; leeway to allow for clock skew with regard to ID Token expiration times.
_disableDeprecationWarnings
optional
(Boolean) Disables the deprecation warnings, defaults to false.
Because of clock skew issues, you may occasionally encounter the error The token was issued in the future. The leeway parameter can be used to allow a few seconds of leeway to ID Token expiration times, to prevent that from occurring.
Scope
The default scope value in auth0.js v9 is openid profile email.
Running Auth0.js locally
If you don’t specify at least the above scope when initializing auth0.js, and you are running your website from http://localhost or http://127.0.0.1, calling the getSSOData() method will result in the following error in the browser console:Consent required. When using getSSOData, the user has to be authenticated with the following scope: openid profile emailThat will not happen when you run your application in production or if you specify the openid profile email scope. You can read more about this in the User consent and third-party applications document.
The authorize() method can be used for logging in users through or social connections as shown in the examples below. This method invokes the /authorize endpoint of the Authentication API, and can take a variety of parameters through the options object.
Parameter
Required
Description
audience
optional
(String) The default audience to be used for requesting API access.
connection
optional
(String) Specifies the connection to use rather than presenting all connections available to the application.
scope
optional
(String) The scopes which you want to request authorization for. These must be separated by a space. You can request any of the standard OIDC scopes about users, such as profile and email, custom claims that must conform to a namespaced format, or any scopes supported by the target API (for example, read:contacts). Include offline_access to get a .
responseType
optional
(String) It can be any space separated list of the values code, token, id_token. It defaults to 'token', unless a redirectUri is provided, then it defaults to 'code'.
clientID
optional
(String) Your Auth0 client ID.
redirectUri
optional
(String) The URL to which Auth0 will redirect the browser after authorization has been granted for the user.
state
optional
(String) An arbitrary value that should be maintained across redirects. It is useful to mitigate CSRF attacks and for any contextual information (for example, a return URL) that you might need after the authentication process is finished. For more information, see State Parameter. auth0.js, when used in single-page applications, handles the state generation and validation automatically if not specified.
prompt
optional
(String) A value of login will force the login page to show regardless of current session. A value of none will attempt to bypass the login prompts if a session already exists (see the silent authentication documentation for more details).
For hosted login, one must call the /authorize() method.webAuth.authorize({//Any additional options can go here});For social logins, the connection parameter will need to be specified:webAuth.authorize({connection: 'twitter'});
For popup authentication the popup.authorize method can be used. Popup authentication cannot be used within hosted login pages. Typically, popup authentication is used by single page apps so the current state is not lost by doing a full page redirection.Default authorization with popup (Universal Login):
Report incorrect code
Copy
Ask AI
webAuth.popup.authorize({ responseType: 'token' redirectUri: 'https://{yourApp}/popup_response_handler.html' //Any additional options can go here}, function(err, authResult) { //do something});
When using popup authentication, you’ll have to provide a redirectUri where the destination page communicates the authorization results back to the callback by using the webAuth.popup.callback method. A simple implementation would be something like this:
An ideal handler would contain only this minimal functionality (that is, avoid reloading the whole application just to handle the response).You will need to add the redirectUri to the application’s Allowed Callback URLs list in the application configuration page on the Dashboard.
Embedded login for web applications uses cross-origin authentication unless you configure a custom domain for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
The login method can be used for embedded login through cross-origin authentication for database connections, using /co/authenticate.
Parameter
Required
Description
username
optional
(String) The username to present for authentication. Eitherusername or email must be present.
email
optional
(String) The email to present for authentication. Eitherusername or email must be present.
password
required
(String) The password to present for authentication.
realm
required
(String) The name of the database connection against which to authenticate.
The crossOriginVerification() method can be used to help provide cross-origin authentication to customers who have third-party cookies disabled in their browsers. Further details about its usage can be read in the cross-origin authentication document.
The buildAuthorizeUrl method can be used to build the /authorize URL, in order to initialize a new transaction. Use this method if you want to implement browser based (passive) authentication.
Report incorrect code
Copy
Ask AI
// Calculate URL to redirect tovar url = webAuth.client.buildAuthorizeUrl({ clientID: '{yourClientId}', // string responseType: 'token id_token', // code redirectUri: 'https://{yourApp}/callback', state: '{yourState}', nonce: '{yourNonce}'});// Redirect to url// ...
The state parameter is an opaque value that Auth0 will send back to you. This method helps prevent CSRF attacks, and it needs to be specified if you redirect to the URL yourself instead of calling webAuth.authorize(). For more information, see State Parameter.
Apps with embedded login must meet two criteria in order to have (SSO).
Both of the applications attempting SSO must be first-party applications. SSO with third-party applications will not work.
They need to make use of custom domains and have both the applications which intend to have SSO as well as the Auth0 tenant on the same domain. Traditionally, Auth0 domains are in the format foo.auth0.com, but custom domains allow you to use the same domain for each of the applications in question as well as your Auth0 tenant, preventing the risk of CSRF attacks.
Our recommendation is to use Universal Login instead of setting up SSO in embedded login scenarios. Universal Login is the most reliable and stable way to perform SSO, and is the only way to do so if you must use multiple domains for your applications, or use third-party applications.
authentication allows users to log in by receiving a one-time password through email or text message. The process will require you to start the passwordless process, generating and dispatching a code to the user (or a code within a link), followed by accepting their credentials through the verification method. That could happen in the form of a login screen which asks for their (email or phone number) and the code you just sent them. It could also be implemented in the form of a passwordless link instead of a code sent to the user. They would simply click the link in their email or text and it would hit your endpoint and verify this data automatically using the same verification method (just without manual entry of a code by the user).In order to use Passwordless, you will want to initialize auth0.js with a redirectUri and to set the responseType: 'token'.
Report incorrect code
Copy
Ask AI
var webAuth = new auth0.WebAuth({ clientID: '{yourClientId}', domain: '{yourDomain}', redirectUri: 'http://example.com', responseType: 'token id_token'});
The first step in passwordless authentication with auth0.js is the passwordlessStart method, which has several parameters which can be passed within its options object:
Parameter
Required
Description
connection
required
(String) Specifies how to send the code/link to the user. Value must be either email or sms.
send
required
(String) Value must be either code or link. If null, a link will be sent.
phoneNumber
optional
(String) The user’s phone number for delivery of a code or link via SMS.
email
optional
(String) The user’s email for delivery of a code or link via email.
Note that exactly one of the optional phoneNumber and email parameters must be sent in order to start the passwordless transaction.
Report incorrect code
Copy
Ask AI
webAuth.passwordlessStart({ connection: 'email', send: 'code', email: 'foo@bar.com' }, function (err,res) { // handle errors or continue });
If sending a code, you will then need to prompt the user to enter that code. You will process the code, and authenticate the user, with the passwordlessLogin method, which has several parameters which can be sent in its options object:
Parameter
Required
Description
connection
required
(String) Specifies how to send the code/link to the user. Value must be either email or sms and the same as the value passed to passwordlessStart.
verificationCode
required
(String) The code sent to the user, either as a code or embedded in a link.
phoneNumber
optional
(String) The user’s phone number to which the code or link was delivered via SMS.
email
optional
(String) The user’s email to which the code or link was delivered via email.
As with passwordlessStart, exactly one of the optional phoneNumber and email parameters must be sent in order to verify the passwordless transaction.In order to use passwordlessLogin, the options redirectUri and responseType must be specified when first initializing WebAuth.
Report incorrect code
Copy
Ask AI
webAuth.passwordlessLogin({ connection: 'email', email: 'foo@bar.com', verificationCode: '389945' }, function (err,res) { // handle errors or continue });
After authentication occurs, you can use the parseHash method to parse a URL hash fragment when the user is redirected back to your application in order to extract the result of an Auth0 authentication response. You may choose to handle this in a callback page that will then redirect to your main application, or in-page, as the situation dictates.The parseHash method takes an options object that contains the following parameters:
Parameter
Required
Description
state
optional
(String) An opaque value the application adds to the initial request that Auth0 includes when redirecting back to the application. This value is used by auth0.js to prevent CSRF attacks.
optional
(String) Used to verify the ID Token
hash
optional
(String) The URL hash (if not provided, window.location.hash will be used by default)
The contents of the authResult object returned by parseHash depend upon which authentication parameters were used. It can include:
Item
Description
accessToken
An for the API, specified by the audience
expiresIn
A string containing the expiration time (in seconds) of the accessToken
idToken
An ID Token JWT containing user profile information
Report incorrect code
Copy
Ask AI
webAuth.parseHash({ hash: window.location.hash }, function(err, authResult) { if (err) { return console.log(err); } webAuth.client.userInfo(authResult.accessToken, function(err, user) { // Now you have the user's information });});
As shown above, the client.userInfo method can be called passing the returned accessToken. It will make a request to the /userinfo endpoint and return the user object, which contains the user’s information, formatted similarly to the below example.
You can now do something else with this information as your application needs, such as acquire the user’s entire set of profile information with the , as described below.
By default (and if responseType contains id_token), auth0.js will generate a random nonce when you call webAuth.authorize, store it in local storage, and pull it out in webAuth.parseHash. The default behavior should work in most cases, but some use cases may require a developer to control the nonce.
If you want to use a developer generated nonce, then you must provide it as an option to both webAuth.authorize and webAuth.parseHash.
webAuth.authorize({<Tooltip tip="Nonce: Arbitrary number issued once in an authentication protocol to detect and prevent replay attacks." cta="View Glossary" href="/docs/glossary?term=nonce">nonce</Tooltip>: '1234', responseType: 'token id_token'}); webAuth.parseHash({nonce: '1234'}, callback);If you’re calling webAuth.checkSession instead of webAuth.authorize, then you only have to specify your custom nonce as an option to checkSession:
Report incorrect code
Copy
Ask AI
webAuth.checkSession({ nonce: '1234',}, function (err, authResult) { ...});
The webAuth.checkSession method will automatically verify that the returned ’s nonce claim is the same as the option.
When Auth0.js is used for embedded login, it employs the /co/authenticate endpoint, which can produce the following errors:
Error descriptions are intended to be human readable. The description should not be parsed by any code and is subject to change at any time.
Status
Code
Description
400
invalid_request
Invalid request body. All and only of client_id, credential_type, username, otp, realm are required.
401
unauthorized_client
Cross origin login not allowed.
400
unsupported_credential_type
Unknown credential type parameter.
400
invalid_request
Unknown realm non-existent-connection.
403
access_denied
Wrong email or password.
403
access_denied
Authentication error
403
blocked_user
Blocked user
401
password_leaked
This login attempt has been blocked because the password you’re using was previously disclosed through a data breach (not in this application).
429
too_many_attempts
Your account has been blocked after multiple consecutive login attempts. We’ve sent you a notification via your preferred contact method with instructions on how to unblock it.
429
too_many_attempts
We have detected suspicious login behavior and further attempts will be blocked. Please contact the administrator.
In addition, you can also get a generic 403 error without an error or error_description property. The response body would just include something similar to the following:
Origin https://test.app is not allowed.
To log out a user, use the logout() method. This method accepts an options object, which can include the following parameters.If the clientID parameter is included, the returnTo URL that is provided must be listed in the Application’s Allowed Logout URLs in the Auth0 dashboard. However, if the clientID parameter is not included, the returnTo URL must be listed in the Allowed Logout URLs at the account level in the Auth0 dashboard.
Report incorrect code
Copy
Ask AI
webAuth.logout({ returnTo: 'some url here', clientID: 'some client ID here'});
The checkSession method allows you to acquire a new token from Auth0 for a user who is already authenticated against Auth0 for your domain. The method accepts any valid OAuth2 parameters that would normally be sent to authorize. If you omit them, it will use the ones provided when initializing Auth0.The call to checkSession can be used to get a new token for the API that was specified as the when webAuth was initialized:
Report incorrect code
Copy
Ask AI
webAuth.checkSession({}, function (err, authResult) { // err if automatic parseHash fails ...});
See Extract the AuthResult and Get User Info for the format of authResult.Or, the token can be acquired for a different API than the one used when initializing webAuth by specifying an audience and scope:
Report incorrect code
Copy
Ask AI
webAuth.checkSession( { audience: `https://mydomain/another-api/˜`, scope: 'read:messages' }, function (err, authResult) { // err if automatic parseHash fails ...});
Note that checkSession() triggers any rules you may have set up, so you should check on your rules in the Dashboard prior to using it.The actual redirect to /authorize happens inside an iframe, so it will not reload your application or redirect away from it.However, the browser must have third-party cookies enabled. Otherwise, checkSession() is unable to access the current user’s session (making it impossible to obtain a new token without displaying anything to the user). The same will happen if users have Safari’s ITP enabled.Remember to add the URL where the authorization request originates from, to the Allowed Web Origins list of your Auth0 application in the Dashboard under your application’s Settings.
If the connection is a social connection and you are using Auth0 dev keys, the checkSession call will always return login_required.
In some multi-application scenarios, where Single Logout is desired (a user logging out of one application needs to be logged out of other applications), an application can be set up to periodically poll Auth0 using checkSession() to see if a session exists. If the session does not exist, you can then log the user out of the application. The same polling method can be used to implement silent authentication for a Single Sign-on (SSO) scenario.The poll interval between checks to checkSession() should be at least 15 minutes between calls to avoid any issues in the future with rate limiting of this call.
If attempting to set up a password reset functionality, you’ll use the changePassword method and pass in an options object, with a connection parameter and an email parameter.
The Management API provides functionality that allows you to link and unlink separate user accounts from different providers and update user metadata. For more information, read User Account Linking.To get started, you first need to obtain a an that can be used to call the Management API. You can do it by specifying the https://{yourDomain}/api/v2/ audience when initializing auth0.js, in which case you will get the access token as part of the authentication flow.If you use custom domains, you will need to instantiate a new copy of webAuth using your Auth0 domain rather than your custom one, for use with the Management API calls, as it only works with Auth0 domains.
Report incorrect code
Copy
Ask AI
var webAuth = new auth0.WebAuth({ clientID: '{yourClientId}', domain: '{yourDomain}', redirectUri: 'http://example.com', audience: `https://{yourDomain}/api/v2/`, scope: 'read:current_user', responseType: 'token id_token'});
In order to get the user profile data, use the getUser() method, with the userId and a callback as parameters. The method returns the user profile. Note that the userID required here will be the same one fetched from the client.userInfo method.
auth0Manage.getUser(userId, cb);
When updating user metadata, you will need to first create a userMetadata object, and then call the patchUserMetadata method, passing it the user id and the userMetadata object you created. The values in this object will overwrite existing values with the same key, or add new ones for those that don’t yet exist in the user metadata. For more information, read Metadata.
auth0Manage.patchUserMetadata(userId, userMetadata, cb);
Linking user accounts will allow a user to authenticate from any of their accounts and no matter which one they use, still pull up the same profile upon login. Auth0 treats all of these accounts as separate profiles by default, so if you wish a user’s accounts to be linked, this is the way to go.The linkUser method accepts two parameters, the primary userId and the secondary user’s ID Token (the token obtained after login with this identity). The user ID in question is the unique identifier for the primary user account. The ID should be passed with the provider prefix, e.g., auth0|1234567890 or facebook|1234567890, when using this method. See User Account Linking for details.
auth0Manage.linkUser(userId, secondaryUserToken, cb);After linking the accounts, the second account will no longer exist as a separate entry in the user database, and will only be accessible as part of the primary one.
When accounts are linked, the secondary account’s metadata is not merged with the primary account’s metadata, and if they are ever unlinked, the secondary account will likewise not retain the primary account’s metadata when it becomes separate again.
Assistant
Responses are generated using AI and may contain mistakes.