Auth0 headless browser sdk
Auth0 is an authentication broker that supports social identity providers as well as enterprise identity providers such as Active Directory, LDAP, Office365, Google Apps, Salesforce.
Auth0.js is a client-side library for Auth0. It allows you to trigger the authentication process and parse the JWT (JSON web token) with just the Auth0
clientID. Once you have the JWT you can use it to authenticate requests to your http API and validate the JWT in your server-side logic with the
The example directory has a ready-to-go app. In order to run it you need node installed, download dependencies with
npm install, then execute
npm run example from the root of this project.
auth0.min.js from the
/build directory and import it to your page.
If you are using browserify install with
npm i auth0-js --production --save.
Note: The following examples use jQuery, but auth0.js is not tied to jQuery and any library can be used with it.
Construct a new instance of the Auth0 client as follows:
This method can be called as indifferently as
Triggers the login on any of your active identity provider as follows:
//trigger login with google$'.login-google'clickauth0loginconnection: 'google-oauth2';;//trigger login with github$'.login-github'clickauth0loginconnection: 'github';;//trigger login with an enterprise connection$'.login-microsoft'clickauth0loginconnection: 'contoso.com';;//trigger login with a db connection$'.login-dbconn'clickauth0loginconnection: 'db-conn'username: $'.username'valpassword: $'.password'val;;//trigger login with a db connection and avoid the redirect (best experience for SPA)$'.login-dbconn'clickauth0loginconnection: 'db-conn'username: $'.username'valpassword: $'.password'val// store in cookies;;//trigger login popup with google$'.login-google-popup'clickepreventDefault;auth0loginconnection: 'google-oauth2'popup: truepopupOptions:width: 450height: 800if erralert"something went wrong: " + errmessage;return;alert'hello ' + profilename;;;
You can also request scopes that are not were not configured for the connection.
//trigger login requesting additional scopes with google$'.login-google'clickauth0loginconnection: 'google-oauth2'connection_scope: '' '';;// alternatively a comma separated list also works$'.login-google'clickauth0loginconnection: 'google-oauth2'connection_scope: '';;
Trigger the login with offline mode support to get the
$'.login-dbconn'clickauth0loginconnection: 'db-conn'username: $'.username'valpassword: $'.password'valscope: 'openid offline_access'// store in cookies// refresh_token is sent because offline_access is set as a scope;;
Passwordless authentication allows users to log in by receiving a one-time password via email or text message.
Once you have configured a passwordless
$'.request-email-link'clickevpreventDefault;auth0startPasswordless email: $'.email-input'valif erralerterrerror_description;return;// the request was successful and you should receive// an email with the link at the specified address;;
After that you can request a passcode to be sent via SMS to a phone number. Ensure the phone number has the proper full-length format
// request a passcode sent via sms to `phoneNumber`// using Twilio's configured connection$'.request-sms-code'clickevpreventDefault;auth0startPasswordlessphoneNumber: $'.phone-input'valif erralerterrerror_description;return;// the request was successful and you should// receive the passcode to the specified phone;;
Once you receive the code you follow using
.login() to authenticate the user using
//submit the passcode to authenticate the phone$'.submit-sms-code'clickevpreventDefault;auth0loginphone: $'.phone-input'valpasscode: $'.sms-code-input'valif erralert"something went wrong: " + errmessage;return;console.logprofile id_token access_token state refresh_token;;;
How does control return back to your app after a login has been attempted? This all depends on which login "mode" you choose to use (Redirect or Popup) and in some cases, which type of connection you're using.
The default mode of the
login method is Redirect Mode. Here two separate "redirect" actions will occur when
login is called. First, the browser will navigate to a separate login page to collect the user's credentials. Once the user successfully logs in, the browser will redirect the user back to your application via the
For example, let's say you've initialized your Auth0 client as shown in the Initialize section above. Then the following call to
login using your
google-oauth2 social connection would result in a redirect to a Google login page and then a redirect back to
http://my-app.com/callback if successful:
If you're building a SPA (Single Page Application) and using Redirect Mode, then your
callbackURL should send the user back to the same page. And because the
callbackOnLocationHash initialization option was set to
true, Auth0 will also append a hash to that URL that will contain an
id_token (the JWT). After control returns to your app, the full user profile can be retrieved via the
$var result = auth0parseHashwindowlocationhash;//use result.id_token to call your rest apiif result && resultid_tokenauth0getProfileresultid_tokenalert'hello ' + profilename;;// If offline_access was a requested scope// You can grab the result.refresh_token hereelse if result && result.erroralert'error: ' + result.error;;
scope option used with the
login method did not contain
openid profile, then the profile will only contain
user_id. In that case just parse the hash to obtain the user ID:
$var result = auth0parseHashwindowlocationhash;if result && resultprofilealert'your user_id is: ' + resultprofilesub;//use result.id_token to call your rest api;;
If there is no hash,
result will be null. If the hash contains the JWT, the
profile field will be populated.
If you're building a regular web application (HTML pages rendered on the server), then
callbackURL should point to a server-side endpoint that will process the successful login, primarily to set some sort of session cookie. In this scenario you should make sure the
callbackOnLocationHash option is
false (or just not specified) when the Auth0 client is created:
var auth0 =domain: 'mine.auth0.com'clientID: 'dsa7d77dsa7d7'callbackURL: ''// callbackOnLocationHash not set (defaults to false);
On successful login, Auth0 will redirect to your
callbackURL with an appended authorization
code query parameter. Unlike the SPA scenario, this
code value should get processed completely server-side.
Note: Server-side processing of the
codelooks something like this: Using whichever Auth0 server-side SDK necessary, the endpoint on the server should exchange the
id_tokenand optionally a full user profile. It should then set some kind of local session cookie, which is what enables a user to be "logged in" to the website and usually contains data from the user profile. It should finally redirect the user back to a meaningful page.
Besides Redirect Mode, the
login method also supports Popup Mode, which you enable by passing
popup: true in the
options argument. In this mode the browser will not be redirected to a separate login page. Instead Auth0 will display a popup window where the user enters their credentials. The advantage of this approach is that the original page (and all of its state) remains intact, which can be important, especially for certain Single Page Apps.
WARNING: While Popup Mode does have the advantage of preserving page state, it has some issues. Often times users have popup blockers that prevent the login page from even displaying. There are also known issues with mobile browsers. For example, in recent versions of Chrome on iOS, the login popup does not get closed properly after login (see an example here). For these reasons, we encourage developers to favor Redirect Mode over Popup Mode, even with Single Page Apps.
In Popup Mode you also have no need to be redirected back to the application, since, once the user has logged in, the popup is simply closed. Instead Auth0 uses the
callback argument to return control to your client-side application, for both failed and successful logins. Along with the
callback should also contain arguments
profile, id_token, access_token, state (and optionally
refresh_token if the
offline_access scope has been requested):
auth0loginpopup: trueconnection: 'google-oauth2'if err// Handle the error!return;// Success!;
The behavior of Redirect and Popup Modes differs if you're using a Database or Active Directory/LDAP connection. Those differences depend on two factors: whether SSO (Single Sign-On) is enabled and whether or not credentials are being directly passed to the
By default SSO is enabled (equivalent to passing the
sso: true option to the
login method). This means that after a successful login, Auth0 will set a special cookie that can be used to automatically log a user onto additional websites that are registered as Auth0 apps. When using either the Database or Active Directory/LDAP connections with SSO enabled, you can still choose to go with Redirect or Popup Mode.
As with other connection types, Redirect Mode will happen by default. The browser will navigate to a login page that will prompt the user for their credentials and then, when login is complete, redirect back to the
callbackURL. However, one of the unique options you have with Database and Active Directory/LDAP connections is that the redirect to the login page can be bypassed if the
password options are passed to the
login method. These values are typically collected via a custom login form in your app:
auth0loginconnection: 'db-conn'username: $'.username'valpassword: $'.password'val// this only gets called if there was a login error;
If the login is successful, the browser will then be redirected to
callbackURL. And as shown above a
callback argument should also be provided to the
login method that handles any authentication errors (without redirecting).
Furthermore, sometimes you don't want a redirect to occur at all after a login. This is often the case with Single Page Apps where a redirect will result in loss of important page state. To handle all login results client-side, simply provide additional parameters to the
auth0loginconnection: 'db-conn'username: $'.username'valpassword: $'.password'valif err// Handle the error!return;// Success!;
callbackapproach is similar to what you'd do in the Popup Mode scenario described earlier, except no popups (or redirects) occur since credentials are provided to the
loginmethod and success and failure is handled in the
You can still do Popup Mode with SSO enabled with a Database or Active Directory/LDAP connection if you want to (but please see the WARNING in the Popup Mode section above). This is similar to the Redirect Mode scenario where you don't have a custom login form, but want to use a popup window to collect the user's credentials, and also want control to return to the client-side code (vs. redirecting to
callbackURL). This behavior would occur if you simply specified the
popup: true option:
auth0loginconnection: 'db-conn'popup: trueif err// Handle the error!return;// Success!;
If you explicitly don't want SSO enabled in your application, you can pass the
sso: false option to the
login method. The result is that when a login occurs, Auth0 performs a CORS POST request (or in IE8 or 9 a JSONP request) against a special "resource owner" endpoint (
/ro), which allows users to authenticate by sending their username and password. Also, no SSO cookie is set.
There are a couple important constraints at play when SSO is disabled:
/roendpoint requires credentials, the
passwordoptions must be passed to the
This leaves you with a call to the
login method that looks something like this:
auth0loginconnection: 'db-conn'sso: falseusername: $'.username'valpassword: $'.password'val// this only gets called if there was a login error;
If the login succeeds, Auth0 will redirect to your
callbackURL and if it fails, control will be given to the
And if you don't want that redirect to occur (i.e. you have a Single Page App), you can use a
callback argument that takes the additional parameters (like what's shown in Popup Mode), and control will go to your callback function with a failed or successful login.
$'.change_password'clickauth0changePasswordconnection: 'db-conn'username: 'firstname.lastname@example.org'password: 'blabla' // new passwordconsole.logerrmessage;;;
A delegation token is a new token for a different service or app/API.
If you just want to get a new token for an addon that you've activated, you can do the following:
var options =id_token: "your id token" // The id_token you have nowapi: 'firebase' // This defaults to the first active addon if any or you can specify this"scope": "openid profile" // default: openid;auth0getDelegationTokenoptions// Call your API using delegationResult.id_token;
If you want to get the token for another API or App:
var options =id_token: "your id token" // The id_token you have nowapi: 'auth0' // This is default when calling another app that doesn't have an addontargetClientId: 'The other client id';auth0getDelegationTokenoptions// Call your API using delegationResult.id_token;
If you want to refresh your existing (not expired) token, you can just do the following:
auth0renewIdTokencurrent_id_token// Get here the new delegationResult.id_token;
If you want to refresh your existing (expired) token, if you have the refresh_token, you can call the following:
auth0refreshTokenrefresh_token// Get here the new delegationResult.id_token;
You can validate a user of a specific connection with his username and password:
auth0validateUserconnection: 'db-conn'username: 'email@example.com'password: 'blabla';
getSSOData fetches Single Sign-On information:
auth0getSSODataif err return console.logerrmessage;expectssoDatassotoexist;;
ssoData object will contain the following fields, for example:
sso: truesessionClients:"jGMow0KO3WDJELW8XIxolqb1XIitjkYL"lastUsedClientID: "jGMow0KO3WDJELW8XIxolqb1XIitjkYL"lastUsedUsername: "firstname.lastname@example.org"lastUsedConnection:name: "Username-Password-Authentication"strategy: "auth0"
Load Active Directory data if available (Kerberos):
When Kerberos is available you can automatically trigger Windows Authentication. As a result the user will immediately be authenticated without taking any action.
auth0getSSODatatrueif !err && ssoData && ssoDataconnectionauth0login connection: ssoDataconnection ;;
grunt dev and point your browser to
http://localhost:9999/test_harness.html to run the test suite.
grunt phantom if you have PhantomJS installed.
grunt integration (or
npm test) if you have SauceLabs account. You will need a
SAUCE_USERNAME env variables.
$ ./bin/version patch$ git push origin master
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.