Angular 2+ Login

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Angular 2.0.1
Show requirements


The best way to have authentication utilities available across the application is to use an Injectable service.

You will need an Auth0Lock instance to receive your Auth0 credentials and an options object. For a full list of Lock's options, see the customization docs.

Your app will need to listen for Lock's authenticated event and have a callback registered to handle authentication. The callback has a single parameter that will have the user's authentication information and it will be invoked once the user is redirected after authenticating.

There is a property on the object that gets returned by Auth0 called idToken which is a JSON Web Token identifying the user. It is this token that can be used to give an indication in your Angular 2 application that the user is authenticated.

For now, store the idToken attribute into localStorage.

In the login method, call to display the login widget.

To check if a user is authenticated, use tokenNotExpired from angular2-jwt, which allows you to see if there is a non-expired JWT in local storage.

// app/auth.service.ts

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

// Avoid name not found warnings
declare var Auth0Lock: any;

export class Auth {
  // Configure Auth0
  lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {});

  constructor() {
    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);

  public login() {
    // Call the show method to display the widget.;

  public authenticated() {
    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired('id_token');

  public logout() {
    // Remove token from localStorage

To use this service, inject the Auth service into your component:


export class AppComponent {
  constructor(private auth: Auth) {}

and into your component's template:

<!-- app/app.template.html -->

<div class="navbar-header">
  <a class="navbar-brand" href="#">Auth0 - Angular 2</a>
  <button class="btn btn-primary btn-margin" (click)="auth.login()" *ngIf="!auth.authenticated()">Log In</button>
  <button class="btn btn-primary btn-margin" (click)="auth.logout()" *ngIf="auth.authenticated()">Log Out</button>

And create your NgModule in your root app module as follows:

// app/app.module.ts

import { NgModule }            from '@angular/core';
import { BrowserModule  }      from '@angular/platform-browser';

import { AppComponent }        from './app.component';
import { HomeComponent }       from './home.component';
import { routing,
         appRoutingProviders } from './app.routes';

  declarations: [
  providers: [
  imports: [
  bootstrap: [AppComponent]
export class AppModule {}

The Lock widget will be displayed when the Login button is clicked.

Use with HashLocationStrategy

In redirect-based authentication flows, the results for the user's authentication transaction come back in a hash fragment. Angular's router automatically cleans up routes on navigation. When using HashLocationStrategy, this means that the application won't see the fragment and the authenticated event won't work properly.

As a workaround, look for an access_token, id_token, or error in the hash when NavigationStart happens and use Lock's resumeAuth method.

// app/auth.service.ts

import { Router, NavigationStart } from '@angular/router';
import 'rxjs/add/operator/filter';

constructor(public router: Router) {
    .filter(event => event instanceof NavigationStart)
    .filter((event: NavigationStart) => (/access_token|id_token|error/).test(event.url))
    .subscribe(() => {
      this.lock.resumeAuth(window.location.hash, (error, authResult) => {
        if (error) return console.log(error);
        localStorage.setItem('id_token', authResult.idToken);

Persisting Application State

Lock uses redirect mode by default, meaning that a full page refresh will occur when users go through the authentication process in your application. This can be undesirable for single page apps, especially if the application contains state that should be displayed to the user again after they authenticate. For example, it may be the case that your users can initiate authentication from an arbitrary route within your single page app and you may want to return them to that location (along with any relevant state) after authentication is complete.

The recommended solution for this is to persist any necessary application state in local storage or a cookie before the user logs in or signs up. With this data, you can provide some custom post-authentication logic in the listener for the authenticated event to allow the user to pick up from where they left off.

In cases where storing application state is not possible, Lock's popup mode can be used. Please note that popup mode is not recommended. Known bugs in certain browsers prevent popup mode from functioning as expected under some circumstances.

Previous Tutorial
1. Introduction
Next Tutorial
3. Custom Login
Use Auth0 for FREECreate free Account