What is auth0-js?
The auth0-js package is a JavaScript client library for integrating Auth0 authentication and authorization services into web applications. It provides a variety of methods for handling user authentication, managing user sessions, and interacting with Auth0's API.
What are auth0-js's main functionalities?
User Authentication
This feature allows you to authenticate users by redirecting them to the Auth0 login page. The code sample demonstrates how to initialize the Auth0 client and trigger the authentication process.
const auth0 = new auth0.WebAuth({
domain: 'YOUR_AUTH0_DOMAIN',
clientID: 'YOUR_CLIENT_ID'
});
auth0.authorize({
redirectUri: 'YOUR_CALLBACK_URL',
responseType: 'token id_token',
scope: 'openid profile email'
});
Handling Authentication Callback
This feature handles the authentication callback after the user has logged in. The code sample shows how to parse the URL hash to extract authentication tokens.
auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
// Save the tokens in local storage or a cookie
} else if (err) {
console.error('Error parsing hash:', err);
}
});
User Logout
This feature allows you to log out users from the application. The code sample demonstrates how to trigger the logout process and redirect the user to a specified URL.
auth0.logout({
returnTo: 'YOUR_RETURN_URL',
clientID: 'YOUR_CLIENT_ID'
});
Silent Authentication
This feature allows you to silently authenticate users without redirecting them to the login page. The code sample shows how to check the user's session and obtain new tokens if needed.
auth0.checkSession({}, (err, authResult) => {
if (err) {
console.error('Error during silent authentication:', err);
} else {
// Use the authResult to get new tokens
}
});
Other packages similar to auth0-js
passport
Passport is a popular authentication middleware for Node.js. It provides a wide range of authentication strategies, including OAuth, OpenID, and more. Unlike auth0-js, which is specific to Auth0, Passport is more flexible and can be used with various authentication providers.
firebase-auth
Firebase Authentication provides backend services for easy use of authentication in web and mobile apps. It supports various authentication methods like email/password, phone, and social providers. Compared to auth0-js, Firebase Authentication is part of the larger Firebase platform, offering more integrated services.
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 clientSecret
.
Example
The example directory has a ready-to-go app. In order to run it you need node installed, then execute npm run example
from the root of this project.
Usage
Take auth0.js
or auth0.min.js
from the build
directory and import it to your page.
If you are using browserify install with npm i auth0.js
.
Note: I use jQuery in these examples but auth0.js doesn't need jquery and you can use anything.
Initialize:
Construct a new instance of the Auth0 client as follows:
<script src="auth0.min.js"></script>
<script type="text/javascript">
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
});
</script>
Login:
Trigger the login on any of your active identity provider as follows:
$('.login-google').click(function () {
auth0.login({
connection: 'google-oauth2'
});
});
$('.login-github').click(function () {
auth0.login({
connection: 'github'
});
});
$('.login-github').click(function () {
auth0.login({
connection: 'contoso.com'
});
});
$('.login-dbconn').click(function () {
auth0.login({
connection: 'github',
username: $('.username').val(),
password: $('.password').val(),
});
});
Parsing JWT profile
Once you have succesfully authenticated, auth0 will redirect to your callbackURL
with a hash containing an access_token and the jwt. You can parse the hash as follows:
$(function () {
auth0.parseHash(function (profile, id_token, access_token, state) {
alert('hello ' + profile.name);
});
});
If there is no hash or the hash doesn't contain the jwt the callback function will not be called. So, it is safe to put this in the same page where you trigger the login.
Sign up (database connections):
If you use Database Connections you can signup as follows:
$('.signup').click(function () {
auth0.signup({
connection: 'google-oauth2',
username: 'foo@bar.com',
password: 'blabla'
}, function (err) {
console.log(err.message);
});
});
After a succesful login it will auto login the user. If you do not want to automatically login the user you have to pass the option auto_login: false
.
Develop
Run grunt dev
and point your browser to http://localhost:9999/
to run the test suite.
Run grunt test
if you have PhantomJS installed.
Do you have issues in some browser? Ask us guidance to test in multiple browsers!
Browser Compatibility
We are using BrowserStack and our own CI server to run the test suite on multiple browsers on every push.
License
The MIT License (MIT)
Copyright (c) 2013 AUTH10 LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.