| lodash | true | ||||||
|---|---|---|---|---|---|---|---|
| title | AngularJS Tutorial | ||||||
| name | Angular.js | ||||||
| alias |
|
||||||
| language |
|
||||||
| framework |
|
||||||
| image | //auth0.com/lib/platforms-collection/img/angular.png | ||||||
| tags |
|
||||||
| snippets |
|
If you have an existing application, follow the steps below.
@@includes.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 and call the signin method to show the Login / SignUp popup.
In the following code, a call is added to the login method of the LoginCtrl controller. On login success, the user's profile and token are saved to localStorage:
@@snippet(meta.snippets.use)@@
This is how it will appear in the browser:
@@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-7.5.min.js"></script> to <script src="//cdn.auth0.com/w2/auth0-6.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 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.
####Add routing
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.tpl.html',
controller: 'LoginCtrl'
});
// Logged in route
$routeProvider.when('/user-info', {
templateUrl: 'userInfo.tpl.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.