| title | AngularJS Tutorial | ||||||
|---|---|---|---|---|---|---|---|
| name | Angular.js | ||||||
| alias |
|
||||||
| language |
|
||||||
| framework |
|
||||||
| image | /media/platforms/angular.png | ||||||
| tags |
|
||||||
| snippets |
|
<%= include('../_includes/_package', { pkgRepo: 'auth0-angular', pkgBranch: 'master', pkgPath: 'examples/widget-redirect', pkgFilePath: null, pkgType: 'js' }) %>
If you have an existing application, follow the steps below.
::: panel-info System Requirements This tutorial and seed project have been tested with the following:
- NodeJS 4.3
- Angular version 1.5.0-rc.0 ::: ${include('./_callback')}
Add the code below to the index.html file to include Auth0's angular module and its dependencies and set the viewport:
${snippet(meta.snippets.dependencies)}
Add the auth0, angular-storage and angular-jwt module dependencies to your angular app definition and configure auth0 by calling the init method of the authProvider:
${snippet(meta.snippets.setup)}
To implement the login, inject the auth service into any controller to use Lock's redirect mode.
${snippet(meta.snippets.use)}
On login success, save the user's profile and token to localStorage:
//app.js
authProvider.on('loginSuccess', function($location, profilePromise, idToken, store) {
console.log("Login Success");
profilePromise.then(function(profile) {
store.set('profile', profile);
store.set('token', idToken);
});
$location.path('/');
});
authProvider.on('loginFailure', function() {
// Error Callback
});${browser}
Note: There are multiple ways of implementing a login. The example above displays the Login Widget. However you may implement your own login UI by changing the line <script src="//cdn.auth0.com/js/lock-9.0.min.js"></script> to <script src="//cdn.auth0.com/w2/auth0-6.8.js"></script>. For more details, see the auth0-angular repo.
To add a logout button, call the auth.signout method to log out the user. Also remove the profile and token information saved in localStorage:
$scope.logout = function() {
auth.signout();
store.remove('profile');
store.remove('token');
}<input type="submit" ng-click="logout()" value="Log out" />To configure secure calls to the API you are creating <%= configuration.api ? ' on ' + configuration.api : '' %>, return on each request the JWT token received on the login by adding jwtInterceptor to the list of $http interceptors:
// app.js
myApp.config(function (authProvider, $routeProvider, $httpProvider, jwtInterceptorProvider) {
// ...
// We're annotating this function so that the `store` is injected correctly when this file is minified
jwtInterceptorProvider.tokenGetter = ['store', function(store) {
// Return the saved token
return store.get('token');
}];
$httpProvider.interceptors.push('jwtInterceptor');
// ...
});Now you can regularly call this API with $http, $resource or any rest client as you would normally and the JWT token will be sent on each request.
After a user has logged in, retrieve from the auth service the profile property, which has all of the user's information:
<span>His name is {{auth.profile.nickname}}</span>// UserInfoCtrl.js
function UserInfoCtrl($scope, auth) {
$scope.auth = auth;
}To discover all the available properties of a user's profile, see Auth0 Normalized User Profile. Note that the properties available depend on the social provider used.
The user's profile and tokens are already saved to localStorage. To keep the user logged in, retrieve the token from localStorage on each page refresh and let auth0-angular know the user is already authenticated:
angular.module('myApp', ['auth0', 'angular-storage', 'angular-jwt'])
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This events gets triggered on refresh or URL change
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
// Either show the login page or use the refresh token to get a new idToken
$location.path('/');
}
}
});
});You have completed the implementation of Login and Signup with Auth0 and AngularJS.
Most apps will need to authenticate users to enable access certain routes.
To enable access to a route:
-
Set the
requiresLoginproperty totrue. -
Add the
$routeProviderconfiguration in theconfigmethod of our app. -
Specify a login page to which users will be redirected if trying to access a route when not authenticated.
// app.js
.config(function (authProvider, $routeProvider, $locationProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'LoginCtrl'
});
// Logged in route
$routeProvider.when('/user-info', {
templateUrl: 'userInfo.html',
controller: 'UserInfoCtrl',
requiresLogin: true
});
authProvider.init({
domain: '<%= account.namespace %>',
clientID: '<%= account.clientId %>',
callbackURL: location.href,
// Here include the URL to redirect to if the user tries to access a resource when not authenticated.
loginUrl: '/login'
});
});Note: If you are using a UI router, see UI Router.
For additional information on how to use this SDK, see Auth0 and AngularJS.