Authentication can be hard, and reinventing the wheel each time it’s needed in an app is certainly no fun. Thankfully, different services and tools can take care of the heavy lifting for us. We’ve already discussed implementing authentication using Firebase, so let’s now explore an alternative: Auth0. Auth0 is a very powerful solution that offers all the features you would expect from an authentication provider (social logins, email/password logins, authorization rules,…)
In this post, we’ll be using the Auth0 Lock widget, which allows to embed a popup inside your app for authentication. You can also implement authentication on Auth0’s hosted login page, in which case you may want to refer to this guide.
This post covers authentication for Angular 2+ apps.
First things first, you’ll need to create an Auth0 account and then create a new Single Page Web Application client.
Once your client is created, you’ll be able to configure the settings according to your preferences. One thing that’ll be important is to add a callback URL that reflects an actual login callback route in your Angular app. Here we’ll create a login route, so we’ll add http://localhost:4200/login
as our only allowed callback URL. Auth0 will redirect to it after authentication.
In your client’s settings, you’ll also have access to the domain and client ID information. Add that information in your app’s environment.ts file:
export const environment = {
production: false,
auth0: {
domain: 'your-awesome-domain.auth0.com',
clientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
callbackURL: 'http://localhost:4200/login'
}
};
You’ll also need three additional packages in your project: auth0-js, auth0-lock and angular2-jwt. Let’s install them into our project using either npm or Yarn:
$ yarn add auth0-js auth0-lock angular2-jwt
# or, using npm:
$ npm install auth0-js auth0-lock angular2-jwt
Now add auth0.min.js to the list of scripts that are included in the build for your app:
...,
"scripts": [
"../node_modules/auth0-js/build/auth0.min.js"
],
...
With Auth0, you can create multiple tenants to accommodate for different deployment environments (development, production, staging,…) Each tenant gets its own domain name (e.g.: my-app-dev.auth0.com
and my-app.auth0.com
). This way, you can create a different client for production, and all you’d need is to populate your production environment file with the different domain name, client id and callback URL.
We’ll add two components to our app: a home component and a login callback component. We can use the Angular CLI to easily generate the new components:
$ ng g c home
$ ng g c login
Next, let’s setup a simple routing module:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent }
];
Let’s also use the Angular CLI to create an Auth service:
$ ng g s auth
At this point, you’ll want to make sure that your routing module is imported in your app module and that the auth service is provided by the app module as well.
Let’s start setting up the auth service:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../environments/environment';
import { tokenNotExpired } from 'angular2-jwt';
import Auth0Lock from 'auth0-lock';
@Injectable()
export class AuthService {
auth0Options = {
theme: {
logo: '/assets/alligator-logo.svg',
primaryColor: '#DFA612'
},
auth: {
redirectUrl: environment.auth0.callbackURL,
responseType: 'token id_token',
audience: https://${environment.auth0.domain}/userinfo,
params: {
scope: 'openid profile'
}
},
autoclose: true,
oidcConformant: true,
};
lock = new Auth0Lock(
environment.auth0.clientId,
environment.auth0.domain,
this.auth0Options
);
constructor(private router: Router) {
this.lock.on('authenticated', (authResult: any) => {
console.log('Nice, it worked!');
this.router.navigate(['/']); // go to the home route
// ...finish implementing authenticated
});
this.lock.on('authorization_error', error => {
console.log('something went wrong', error);
}); }
login() {
this.lock.show();
}
logout() {
// ...implement logout
}
Here are a few things to note:
We can now inject the auth service in our home component:
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
export class HomeComponent {
And let’s add login and logout buttons in to the template:
<button
*ngIf="!auth.isAuthenticated()"
(click)="auth.login()">
Sign Up or Login
</button>
<button
*ngIf="auth.isAuthenticated()"
(click)="auth.logout()">
Logout
</button>
With our basic auth service in place, the Auth0 embed is already working and we can signup or login:
Let’s complete our auth service implementation. For our example, we’ll save the JSON Web Token that Auth0 returns to local storage. That token can then be added to an Authorization header using the Bearer prefix on HTTP requests to your backend API. It’ll then be the responsibility of the backend to ensure that the token is valid. We’ll also get the account’s profile information that we requested using scopes and save it to local storage.
First, the logic on successful authenticated events:
this.lock.on('authenticated', (authResult: any) => {
this.lock.getUserInfo(authResult.accessToken, (error, profile) => {
if (error) {
throw new Error(error);
}
localStorage.setItem('token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
this.router.navigate(['/']);
Here we’re calling getUserInfo on the lock instance and passing-in the access token returned from the successful authentication. getUserInfo gives us access to the profile information for the user.
Our isAuthenticated method is useful for our app to know if there’s an authenticated used or not and adapt the UI in consequence.
To implement it, we’ll make use of angular2-jwt’s tokenNotExpired
method. It’ll return false if there’s no token or if the token is expired:
isAuthenticated() {
return tokenNotExpired();
}
Since using JWTs for authentication is stateless, all we have to do to logout is to remove the token and profile from local storage:
logout() {
localStorage.removeItem('profile');
localStorage.removeItem('token');
}
🔑 And there you have it! Simple authentication for your apps.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I am interesting with this tutorial, is there a GitHub for this tutorial? in addition, is there any update? because this is 2017’s version