AngularJS: Login
Sample Project
Download a sample project specific to this tutorial configured with your Auth0 API Keys.
- AngularJS 1.6
Before you start
This guide walks you through setting up authentication and authorization in your AngularJS apps with Auth0. If you are new to Auth0, check our Overview. For a complete picture of authentication and authorization for all Single Page Applications, check our SPA + API documentation.
Auth0 uses OAuth. If you want to learn more about the OAuth flows used by Single Page Applications, read about Authentication for Client-side Web Apps.
Get Your Application Keys
When you signed up for Auth0, you created a new client.
Your application needs some details about this client to communicate with Auth0. You can get these details from the Settings section for your client in the Auth0 dashboard.
You need the following information:
- Client ID
- Domain
Configure Callback URLs
A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.
You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Client Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.
Install auth0.js
You need the auth0.js library to integrate Auth0 into your application.
Install auth0.js using npm or yarn.
# installation with npm
npm install --save auth0-js
# installation with yarn
yarn add auth0-js
Once you install auth0.js, add it to your build system or bring it in to your project with a script tag.
<script type="text/javascript" src="node_modules/auth0-js/build/auth0.js"></script>
If you do not want to use a package manager, you can retrieve auth0.js from Auth0's CDN.
<script src="https://cdn.auth0.com/js/auth0/9.3.1/auth0.min.js"></script>
Install angular-auth0
To use auth0.js in your AngularJS application, you need a thin wrapper called angular-auth0.
Install angular-auth0 using npm or yarn.
# installation with npm
npm install --save angular-auth0
# installation with yarn
yarn add angular-auth0
Once you install angular-auth0, add it to your build system or bring it in to your project as a script tag.
<script type="text/javascript" src="node_modules/angular-auth0/dist/angular-auth0.js"></script>
Add Authentication with Auth0
Universal login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your AngularJS application.
When a user logs in, Auth0 returns three items:
access_token
: to learn more, see the Access Token documentationid_token
: to learn more, see the ID Token documentationexpires_in
: the number of seconds before the Access Token expires
You can use these items in your application to set up and manage authentication.
Configure angular-auth0
The angular-auth0 wrapper comes with a provider called angularAuth0Provider
. The provider has an init
method which takes a configuration object used to create an instance of the WebAuth
object from auth0.js.
Inject the angularAuth0Provider
provider.
In the options object you pass to angularAuth0Provider.init
, include the following information:
- Configuration for your client and domain
- Response type, to show that you need a user's Access Token and an ID Token after authentication
- Audience and scope, which specify that authentication must be OIDC-conformant
- The URL where you want to redirect your users after authentication.
// app/app.js
(function () {
'use strict';
angular
.module('app', ['auth0.auth0', 'ui.router'])
.config(config);
config.$inject = [
'$stateProvider',
'$locationProvider',
'$urlRouterProvider',
'angularAuth0Provider'
];
function config(
$stateProvider,
$locationProvider,
$urlRouterProvider,
angularAuth0Provider
) {
$stateProvider
.state('home', {
url: '/',
controller: 'HomeController',
templateUrl: 'app/home/home.html',
controllerAs: 'vm'
})
.state('callback', {
url: '/callback',
controller: 'CallbackController',
templateUrl: 'app/callback/callback.html',
controllerAs: 'vm'
});
// Initialization for the angular-auth0 library
angularAuth0Provider.init({
clientID: 'YOUR_CLIENT_ID',
domain: 'YOUR_AUTH0_DOMAIN',
responseType: 'token id_token',
audience: 'https://YOUR_AUTH0_DOMAIN/userinfo',
redirectUri: 'http://localhost:3000/callback',
scope: 'openid'
});
$urlRouterProvider.otherwise('/');
$locationProvider.hashPrefix('');
/// Comment out the line below to run the app
// without HTML5 mode (will use hashes in routes)
$locationProvider.html5Mode(true);
}
})();
Create an Authentication Service
Create a reusable service to manage and coordinate user authentication. You can call the service's methods from your application.
Create a service and provide a login
method that calls the authorize
method from angular-auth0.
// app/auth/auth.service.js
(function () {
'use strict';
angular
.module('app')
.service('authService', authService);
authService.$inject = ['$state', 'angularAuth0', '$timeout'];
function authService($state, angularAuth0, $timeout) {
function login() {
angularAuth0.authorize();
}
return {
login: login
}
}
})();
Finish the Service
Add more methods to the authService
service to handle authentication in the app.
The example below shows the following methods:
handleAuthentication
: looks for the result of authentication in the URL hash. Then, the result is processed with theparseHash
method from auth0.jssetSession
: sets the user's Access Token and ID Token, and the Access Token's expiry timelogout
: removes the user's tokens and expiry time from browser storageisAuthenticated
: checks whether the expiry time for the user's Access Token has passed
// app/auth/auth.service.js
(function () {
'use strict';
angular
.module('app')
.service('authService', authService);
authService.$inject = ['$state', 'angularAuth0', '$timeout'];
function authService($state, angularAuth0, $timeout) {
// ...
function handleAuthentication() {
angularAuth0.parseHash(function(err, authResult) {
if (authResult && authResult.accessToken && authResult.idToken) {
setSession(authResult);
$state.go('home');
} else if (err) {
$timeout(function() {
$state.go('home');
});
console.log(err);
}
});
}
function setSession(authResult) {
// Set the time that the Access Token will expire at
let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
}
function logout() {
// Remove tokens and expiry time from localStorage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
}
function isAuthenticated() {
// Check whether the current time is past the
// Access Token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
return {
// ...
handleAuthentication: handleAuthentication,
logout: logout,
isAuthenticated: isAuthenticated
}
}
})();
Provide a Login Control
Provide a component with controls for the user to log in and log out.
<!-- app/navbar/navbar.html -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Auth0 - AngularJS</a>
<button
class="btn btn-primary btn-margin"
ui-sref="home">
Home
</button>
<button
class="btn btn-primary btn-margin"
ng-if="!vm.auth.isAuthenticated()"
ng-click="vm.auth.login()">
Log In
</button>
<button
class="btn btn-primary btn-margin"
ng-if="vm.auth.isAuthenticated()"
ng-click="vm.auth.logout()">
Log Out
</button>
</div>
</div>
</nav>
// app/navbar/navbar.directive.js
(function() {
'use strict';
angular
.module('app')
.directive('navbar', navbar);
function navbar() {
return {
templateUrl: 'app/navbar/navbar.html',
controller: navbarController,
controllerAs: 'vm'
}
}
navbarController.$inject = ['authService'];
function navbarController(authService) {
var vm = this;
vm.auth = authService;
}
})();
Depending on whether the user is authenticated or not, they see the Log Out or Log In button. The ng-click
events on the buttons make calls to the authService
service to let the user log in or out. When the user clicks Log In, they are redirected to the login page.
Add a Callback Component
When you use the login page, your users are taken away from your application. After they authenticate, they are automatically returned to your application and a client-side session is set for them.
You can select any URL in your application for your users to return to. We recommend creating a dedicated callback route. If you create a single callback route:
- You don't have to whitelist many, sometimes unknown, callback URLs.
- You can display a loading indicator while the application sets up a client-side session.
Create a controller and a template to use for a callback route. Add a loading indicator.
// app/callback/callback.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('CallbackController', callbackController);
function callbackController() {}
})();
<!-- app/callback/callback.html -->
<div class="loading">
<img src="assets/loading.svg" alt="loading">
</div>
After authentication, your users are taken to the /callback
route. They see the loading indicator while the application sets up a client-side session for them. After the session is set up, the users are redirected to the /home
route.
Process the Authentication Result
When a user authenticates at the login page, they are redirected to your application. Their URL contains a hash fragment with their authentication information. The handleAuthentication
method in the authService
service processes the hash.
Call the handleAuthentication
method in your app's run block. The method processess the authentication hash while your app loads.
// app/app.run.js
(function () {
'use strict';
angular
.module('app')
.run(run);
run.$inject = ['authService'];
function run(authService) {
// Handle the authentication
// result in the hash
authService.handleAuthentication();
}
})();