Authenticating Firebase and Angular with Auth0: Part 2

This article was originally published on the blog, and is republished here with permission.
In this two-part tutorial series, we’ll learn how to build an application that secures a Node back end and an Angular front end with Auth0 authentication. Our server and app will also authenticate a Firebase Cloud Firestore database with custom tokens so that users can leave realtime comments in a secure manner after logging in with Auth0. The Angular application code can be found at the angular-firebase GitHub repo and the Node API can be found in the firebase-auth0-nodeserver repo.
The first part of our tutorial, Authenticating Firebase and Angular with Auth0: Part 1, covered:

intro and setup for Auth0 and Firebase
implementing a secure Node API that mints custom Firebase tokens and provides data for our app
Angular application architecture with modules and lazy loading
Angular authentication with Auth0 with service and route guard
shared Angular components and API service.

Authenticating Firebase and Angular with Auth0: Part 2
Part 2 of our tutorial will cover:

Displaying Dogs: Async and NgIfElse
Dog Details with Route Parameters
Comment Model Class
Firebase Cloud Firestore and Rules
Comments Component
Comment Form Component
Realtime Comments

Our completed app will look something like this:

Let’s pick up right where we left off at the end of Authenticating Firebase and Angular with Auth0: Part 1.
Displaying Dogs: Async and NgIfElse
Let’s implement the home page of our app — the dogs listing. We created the scaffolding for this component when we set up our Angular app’s architecture.
Important Note: Make sure your Node.js API is running. If you need a refresher on the API, refer to How to Authenticate Firebase and Angular with Auth0: Part 1 – Node API.
Dogs Component Class
Open the dogs.component.ts class file now and implement this code:
// src/app/dogs/dogs/dogs.component.ts
import { Component, OnInit } from ‘@angular/core’;
import { Title } from ‘@angular/platform-browser’;
import { ApiService } from ‘../../core/api.service’;
import { Dog } from ‘./../../core/dog’;
import { Observable } from ‘rxjs/Observable’;
import { tap, catchError } from ‘rxjs/operators’;

selector: ‘app-dogs’,
templateUrl: ‘./dogs.component.html’
export class DogsComponent implements OnInit {
pageTitle = ‘Popular Dogs’;
dogsList$: Observable;
loading = true;
error: boolean;

private title: Title,
private api: ApiService
) {
this.dogsList$ = api.getDogs$().pipe(
tap(val => this._onNext(val)),
catchError((err, caught) => this._onError(err, caught))

ngOnInit() {

private _onNext(val: Dog[]) {
this.loading = false;

private _onError(err, caught): Observable<any> {
this.loading = false;
this.error = true;
return Observable.throw(‘An error occurred fetching dogs data.’);


After our imports, we’ll set up some local properties:

pageTitle: to set our page’s <h1> and <title>
dogsList$: the observable returned by our API HTTP request to fetch the dogs listing data
loading: to show a loading icon while the API request is being made
error: to display an error if something goes wrong fetching data from the API.

We’re going to be using the declarative async pipe to respond to the dogsList$ observable returned by our API GET request. With the async pipe, we don’t need to subscribe or unsubscribe in our DogsComponent class: the subscription process will be managed automatically! We just need to set up our observable.
We’ll make Title and ApiService available to our class by passing them to the constructor, and then set up our dogsList$ observable. We’ll use RxJS operators tap (previously known as the do operator) and catchError to call handler functions. The tap operator executes side effects but does not affect the emitted data, so it’s ideal for setting other properties. The _onNext() function will set loading to false (since data has been successfully emitted). The _onError() function will set loading and error appropriately and throw an error. As mentioned before, we don’t need to subscribe or unsubscribe from the dogsList$ observable because the async pipe (which we’ll add in the template) will handle that for us.
On initialization of our component, we’ll use ngOnInit() to spy on the OnInit lifecycle hook to set the document <title>.
That’s it for our Dogs component class!
Dogs Component Template
Let’s move on to the template at dogs.component.html:
<!– src/app/dogs/dogs/dogs.component.html –>
<h1 class=”text-center">{{ pageTitle }}</h1>

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">
<p class="lead">
These were the top <a href="">10 most popular dog breeds in the United States in 2016</a>, ranked by the American Kennel Club (AKC).
<div class="row mb-3">
<div *ngFor="let dog of dogsList" class="col-xs-12 col-sm-6 col-md-4">
<div class="card my-2">
<img class="card-img-top" [src]="dog.image" [alt]="dog.breed">
<div class="card-body">
<h5 class="card-title">#{{ dog.rank }}: {{ dog.breed }}</h5>
<p class="text-right mb-0">
<a class="btn btn-primary" [routerLink]="[‘/dog’, dog.rank]">Learn more</a>


There are a couple things in this template that we’ll take a closer look at:

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">

<div *ngFor="let dog of dogsList" …>

This code does some very useful things declaratively. Let’s explore.
First we have an <ng-template> element with a template reference variable (#noDogs). The <ng-template> element is never rendered directly. It’s intended to be used with structural directives (such as NgIf). In this case, we’ve created an embedded view with <ng-template #noDogs> which contains both the loading and error components. Each of these components will render based on a condition. The noDogs embedded view itself will not render unless instructed to.
So how (and when) do we tell this view to render?
The next <div *ngIf="… is actually an NgIfElse using the asterisk prefix as syntactic sugar. We’re also using the async pipe with our dogsList$ observable and setting a variable so we can reference the stream’s emitted values in our template (as dogsList). If something goes wrong with the dogsList$ observable, we have an else noDogs statement that tells the template to render the <ng-template #noDogs> view. This would be true before the data has been successfully fetched from the API, or if an error was thrown by the observable.
If dogsList$ | async has successfully emitted a value, the div will render and we can iterate over our dogsList value (which is expected to be an array of Dogs, as specified in our component class) using the NgForOf (*ngFor) structural directive to display each dog’s information.
As you can see in the remaining HTML, each dog will be displayed with a picture, rank, breed, and a link to their individual detail page, which we’ll create next.
View the Dogs component in the browser by navigating to your app’s homepage at http://localhost:4200. The Angular app should make a request to the API to fetch the list of dogs and display them!
Note: We’ve also included the <app-comments> component. Since we’ve generated this component but haven’t implemented its functionality yet, it should show up in the UI as text that says “Comments works!”
To test error handling, you can stop the API server (Ctrl+c in the server’s command prompt or terminal). Then try reloading the page. The error component should display since the API cannot be reached, and we should see the appropriate errors in the browser console:

Continue reading %Authenticating Firebase and Angular with Auth0: Part 2%


Authenticating Firebase and Angular with Auth0: Part 1

This article was originally published on the blog, and is republished here with permission.
In this 2-part tutorial series, we’ll learn how to build an application that secures a Node back end and an Angular front end with Auth0 authentication. Our server and app will also authenticate a Firebase Cloud Firestore database with custom tokens so that users can leave realtime comments in a secure manner after logging in with Auth0.
The Angular application code can be found at the angular-firebase GitHub repo and the Node API can be found in the firebase-auth0-nodeserver repo.
Authenticating Firebase and Angular with Auth0: Part 1
Part 1 of our tutorial will cover:

Firebase and Auth0
What We’ll Build
Angular CLI
Auth0 Client and API
Firebase Project with Service Account
Node API
Set Up Angular App
Angular App Architecture
Implement Shared Modules
Implement Routing and Lazy Loaded Modules
Loading and Error Components
Authentication Logic
Core Logic
Next Steps

Firebase and Auth0
Firebase is a mobile and web application development platform. Firebase was acquired by Google in 2014, and continues to be developed under the Google umbrella. Firebase provides NoSQL databases (RTDB, or Realtime Database and Cloud Firestore, in beta at the time of writing) hosted in the cloud and connected using web sockets to provide realtime capabilities to apps.
Auth0 is a cloud-based platform that provides authentication and authorization as a service. As an authentication provider, Auth0 enables developers to easily implement and customize login and authorization security for their apps.
Choosing Auth0 + Firebase Authentication
If you’re already familiar with Firebase’s offerings, you might be asking: why would we implement Auth0 with custom tokens in Firebase instead of sticking with Firebase’s built-in authentication by itself?
Firstly, there is an important distinction to make here. Using Auth0 to secure Firebase does not mean you are not using Firebase auth. Firebase has a custom authentication approach that allows developers to integrate their preferred identity solution with Firebase auth. This approach enables developers to implement Firebase auth so that it functions seamlessly with proprietary systems or other authentication providers.
There are many potential reasons we might want to integrate Auth0 with Firebase authentication. Alternatively, there are scenarios where using basic Firebase auth by itself could suffice. Let’s explore.
You can use Firebase’s built-in authentication by itself if you:

Only want to authenticate Firebase RTDB or Firestore and have no need to authenticate additional back ends
Only need a small handful of login options and do not need enterprise identity providers, integration with your own user storage databases, etc.
Do not need extensive user management, profile enrichment, etc. and are comfortable managing users strictly through an API
Have no need to customize authentication flows
Do not need to adhere to compliance regulations regarding the storage of user data.

You should consider Auth0 with a custom Firebase token if you:

Already have Auth0 implemented and want to add realtime capabilities to your app
Need to easily use issued tokens to secure a back end that is not provided by Firebase
Need to integrate social identity providers beyond just Google, Facebook, Twitter, and GitHub
Need to integrate enterprise identity providers, such as Active Directory, LDAP, ADFS, SAMLP, etc.
Need a customized authentication flow
Need robust user management with APIs and an admin-friendly dashboard
Want to be able to dynamically enrich user profiles
Want features like customizable passwordless login, multifactor authentication, breached password security, anomaly detection, etc.
Must adhere to compliance regulations such as HIPAA, GDPR, SOC2, etc.

Essentially, Firebase’s basic authentication providers should suffice if you have a very simple app with bare-bones authentication needs and are only using Firebase databases. However, should you need more than that, Firebase offers a great way to use their services with other authentication solutions. This is a much more realistic scenario that many developers will be faced with, so we’ll explore it in detail here.
What We’ll Build
We’re going to build a Node.js API secured with Auth0 that mints custom Firebase tokens and also returns data on ten different dog breeds.
We’ll also build an Angular front end app called “Popular Dogs” that displays information about the ten most popular dogs in 2016, ranked by public popularity by the American Kennel Club (AKC). Our app will be secured by Auth0, call the Node API to fetch dog data, and call the API to acquire Firebase tokens to authorize users to add and delete comments in realtime with Cloud Firestore. The app will use shared modules as well as implement lazy loading.

To implement the app, you will need the following:

Angular CLI
A free Auth0 account with a Client and an API configured
A free Firebase project with a service account

Let’s get started!
Angular CLI
Make sure you have Node.js with NPM installed on your local machine. Run the following command to install the Angular CLI globally:
$ npm install -g @angular/cli@latest

We will generate our Angular app and nearly all of its architecture using the CLI.
Auth0 Client and API
You’ll need an Auth0 account to manage authentication. You can sign up for a free account here.

Next, set up an Auth0 client app and API so Auth0 can interface with the Angular app and Node API.
Set Up an Auth0 Client

Go to your Auth0 Dashboard and click the Create a New Client button.
Name your new app (something like Angular Firebase) and select Single Page Web Applications.
In the Settings for your new Auth0 client app, add http://localhost:4200/callback to the Allowed Callback URLs.
Enable the toggle for Use Auth0 instead of the IdP to do Single Sign On.
At the bottom of the Settings section, click “Show Advanced Settings". Choose the OAuth tab and verify that the JsonWebToken Signature Algorithm is set to “RS256”.
If you’d like, you can set up some social connections. You can then enable them for your app in the Client options under the Connections tab. The example shown in the screenshot above uses username/password database, Facebook, Google, and Twitter.

Note: For production, make sure you set up your own social keys and do not leave social connections set to use Auth0 dev keys.
Set Up an Auth0 API

Go to APIs in your Auth0 dashboard and click on the “Create API” button. Enter a name for the API, such as Firebase Dogs API. Set the Identifier to your API endpoint URL. In this tutorial, our API identifier is http://localhost:1337/. The Signing Algorithm should be “RS256”.
You can consult the Node.js example under the Quick Start tab in your new API’s settings. In the next steps, we’ll implement our Node API in this fashion using Express, express-jwt, and jwks-rsa.

We’re now ready to implement Auth0 authentication on both our Angular client and Node back-end API.
Firebase Project with Service Account
Next you will need a free Firebase project.
Create a Firebase Project

Go to the Firebase Console and sign in with your Google account.
Click on Add Project.
In the dialog that pops up, give your project a name (such as Angular Firebase Auth0). A project ID will be generated based on the name you chose. You can then select your country/region.
Click the Create Project button.

Generate an Admin SDK Key
In order to mint custom Firebase tokens, you’ll need access to the Firebase Admin SDK. To obtain access, you must create a service account in your new Firebase project.
Click on the gear wheel icon next to your Project Overview in the Firebase console sidebar and select Project Settings from the menu that appears:

In the settings view, click the Service Accounts tab. The Firebase Admin SDK UI will appear, showing a configuration code snippet. Node.js is selected by default. This is the technology we want, and we will implement it in our Node API. Click on the Generate New Private Key button.
A dialog will appear warning you to store your private key confidentially. We will take care never to check this key into a public repository. Click on the Generate Key button to download the key as a .json file. We will add this file to our Node API shortly.
Node API
The completed Node.js API for this tutorial can be found at the firebase-auth0-nodeserver GitHub repo. Let’s learn how to build this API.
Node API File Structure
We’ll want to set up the following file structure:

You can generate the necessary folders and files with the command line like so:
$ mkdir firebase-auth0-nodeserver
$ cd firebase-auth0-nodeserver
$ mkdir firebase
$ touch firebase/.gitignore
$ touch .gitignore
$ touch config.js
$ touch dogs.json
$ touch package.json
$ touch routes.js
$ touch server.js

Firebase Admin SDK Key and Git Ignore
Now move the Firebase Admin SDK .json key file you downloaded earlier into the firebase folder. We will take care to make sure the folder is checked in, but its contents are never pushed to a repo using the firebase/.gitignore like so:
# firebase/.gitignore

This .gitignore configuration ensures that Git will ignore any files and folders inside the firebase directory except for the .gitignore file itself. This allows us to commit an (essentially) empty folder. Our .json Firebase Admin SDK key can live in this folder and we won’t have to worry about gitignoring it by filename.
Note: This is particularly useful if we have the project pulled down on multiple machines and have different keys (with different filenames) generated.
Next let’s add the code for the root directory’s .gitignore:
# .gitignore

Dogs JSON Data
Next we’ll add the data for ten dog breeds. For brevity, you can simply copy and paste this data into your dogs.json file.
Let’s add our package.json file like so:
"name": "firebase-auth0-nodeserver",
"version": "0.1.0",
"description": "Node.js server that authenticates with an Auth0 access token and returns a Firebase auth token.",
"repository": "",
"main": "server.js",
"scripts": {
"start": "node server"
"author": "Auth0",
"license": "MIT",
"dependencies": {},
"devDependencies": {}

We’ll install the dependencies with the command line and latest versions will be saved automatically to the package.json file:
$ npm install –save body-parser cors express express-jwt jwks-rsa firebase-admin

We’ll need body-parser, cors, and express to serve our API endpoints. Authentication will rely on express-jwt and jwks-rsa, while Firebase token minting is implemented with the firebase-admin SDK (which we’ll have access to using the key we generated).
In the config.js file, add the following code and replace the placeholder values with your own settings:
// config.js
module.exports = {
AUTH0_DOMAIN: ‘<Auth0 Domain>’, // e.g.,
AUTH0_API_AUDIENCE: ‘<Auth0 API Audience>’, // e.g., http://localhost:1337/
FIREBASE_KEY: ‘./firebase/<Firebase JSON>’, // e.g., your-project-firebase-adminsdk-xxxxx-xxxxxxxxxx.json
FIREBASE_DB: ‘<Firebase Database URL>’ // e.g.,

With our data, configuration, and dependencies in place, we can now implement our Node server. Open the server.js file and add:
// server.js
// Modules
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);

// App
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

// Set port
const port = process.env.PORT || ‘1337’;
app.set(‘port’, port);

// Routes

// Server
app.listen(port, () => console.log(`Server running on localhost:${port}`));

This will launch our Node server with Express at http://localhost:1337/.
Note: Notice that this is the API identifier we set up in Auth0.
API Routes
Next open the routes.js file. This is where we’ll define our API endpoints, secure them, and mint custom Firebase tokens. Add the following code:
// routes.js
// Dependencies
const jwt = require(‘express-jwt’);
const jwks = require(‘jwks-rsa’);
const firebaseAdmin = require(‘firebase-admin’);
// Config
const config = require(‘./config’);

module.exports = function(app) {
// Auth0 athentication middleware
const jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${config.AUTH0_DOMAIN}/.well-known/jwks.json`
audience: config.AUTH0_API_AUDIENCE,
issuer: `https://${config.AUTH0_DOMAIN}/`,
algorithm: ‘RS256’

// Initialize Firebase Admin with service account
const serviceAccount = require(config.FIREBASE_KEY);
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: config.FIREBASE_DB

// GET object containing Firebase custom token
app.get(‘/auth/firebase’, jwtCheck, (req, res) => {
// Create UID from authenticated Auth0 user
const uid = req.user.sub;
// Mint token using Firebase Admin SDK
.then(customToken =>
// Response must be an object or Firebase errors
res.json({firebaseToken: customToken})
.catch(err =>
message: ‘Something went wrong acquiring a Firebase token.’,
error: err

// Set up dogs JSON data for API
const dogs = require(‘./dogs.json’);
const getDogsBasic = () => {
const dogsBasicArr = => {
return {
rank: dog.rank,
breed: dog.breed,
image: dog.image
return dogsBasicArr;

// GET dogs (public)
app.get(‘/api/dogs’, (req, res) => {

// GET dog details by rank (private)
app.get(‘/api/dog/:rank’, jwtCheck, (req, res) => {
const rank = req.params.rank * 1;
const thisDog = dogs.find(dog => dog.rank === rank);

At a high level, our routes file does the following:

Sets up authentication checking to ensure that only logged in users can access routes with jwtCheck middleware
Initializes the Firebase Admin SDK with the private key generated from the Firebase project service account
Provides a secure GET endpoint that returns a custom Firebase token
Provides a public GET* endpoint that returns a short version of the dogs data
Provides a secure GET* endpoint that returns a specific dog’s detailed data, requested by rank.

*Endpoints use variations of the same base dataset to simulate a more complex API.
You can read the code comments for more detail.
Serve the API
You can serve the Node API by running:
$ node server

The API will then be available at http://localhost:1337.
Note: If you try to access secure routes in the browser, you should receive a 401 Unauthorized error.
That’s it for our server! Keep the API running so that it will be accessible to the Angular app, which we’ll set up next.
Continue reading %Authenticating Firebase and Angular with Auth0: Part 1%


Authentication with Angular and Auth0

This article was originally published on the blog, and is republished here with permission.
In this tutorial, we’re going to build an Angular application and add login functionality using token-based authentication with Auth0.
You can check out the completed code example from our GitHub repo.
The Angular Ecosystem
AngularJS 1.x was highly regarded as a robust framework for building single-page applications (SPAs). It did a lot of things well, fell short on some, but overall allowed developers to quickly build powerful applications.
While AngularJS (1.x) is a framework, Angular is an entire platform for building modern applications. Alongside the core Angular library, the platform ships with a powerful command line interface (CLI) called Angular CLI that allows developers to easily scaffold their applications as well as control the build system. Angular Platform Server brings server-side rendering to Angular applications. Angular Material is the official implementation of Google’s Material Design, which allows developers to build beautiful applications with ease.
Our App: Daily Deals

The app we’re building today is called Daily Deals. The Daily Deals app displays a list of deals and discounts on various products. We’ll have a list of publicly available deals that anyone can see and a list of private deals available only to registered members. The private deals are exclusive to registered members, and should hopefully be better.
Serving the Daily Deals
We’ll have to get our daily deals from somewhere. Let’s build a very simple Node.js back end to serve the deals. We’ll have a publicly accessible route serving public deals and a protected route that can only be called by authenticated users. For now, we’ll make both of the routes public and worry about the authentication piece later. Take a look at our implementation below:
‘use strict’;
// Load dependencies
const express = require(‘express’);
const app = express();
const cors = require(‘cors’);
const bodyParser = require(‘body-parser’);

app.use(bodyParser.urlencoded({ extended: true }));

// Public route
app.get(‘/api/deals/public’, (req, res)=>{
let deals = [
// Array of public deals here

// Private route
app.get(‘/api/deals/private’, (req,res)=>{
let deals = [
// Array of Private Deals here

console.log(‘Serving deals on localhost:3001’);

Both our server and the Angular app we are building will require Node.js and NPM, so be sure to have those installed before continuing. Check out the GitHub repo to get our list of daily deals or create your own. The model for each deal will be as follows:
id: 1234,
name: ‘Name of Product’,
description: ‘Description of Product’,
originalPrice: 19.99, // Original price of product
salePrice: 9.99 // Sale price of product

When you’re happy with the public and private deals, launch the server by running node server and navigate to both localhost:3001/api/deals/public and localhost:3001/api/deals/private to make sure you can see the list of deals you added. Next, let’s set up our Angular front end.
Angular Front End Setup
One of the best ways to start building a new Angular app is with the official Angular CLI. The CLI can take care of scaffolding the initial app, adding additional components, takes care of the build system and much more. In this tutorial, we’ll scaffold our initial app with the CLI.
If you don’t already have it installed, run:
npm install @angular/cli -g

This installs the Angular CLI globally. We’ll interact with the CLI using the ng command. To create a new application, choose a directory and run:
ng new ng2auth –routing –skip-tests

This will create a new Angular application with routing and no initial test files for the root component. The app will be created in its own folder in the current directory, and the CLI will download all of the required npm packages and basically set everything up for us.
Once ng new is finished, enter the new directory and run the ng serve command and the Webpack based build system will take care of compiling our app from TypeScript to JavaScript and will serve our app on localhost:4200. The ng serve command will also kick off a live sync process, so any time we make a change our app will automatically recompile.
Let’s head over the localhost:4200 for now to make sure that everything is working as expected so far. If you see a message saying “app works!”, you’re golden. Next, let’s examine how our Angular app is scaffolded.
The ng new command scaffolded our Angular app and added a lot of files. Many of these we can ignore for now like the e2e folder, which would contain our end-to-end tests. Open up the src directory. In the src directory, we can see some familiar files like index.html, styles.css, and so on. Open up the app directory.
The app directory contains the bulk of our application. By default, we’re presented with the following files:

app.component.css – Holds the CSS styles for our root component
app.component.html – Holds the HTML view for our root component
app.component.ts – Holds the TypeScript logic for our root component class
app.module.ts – Defines our global app dependencies
app-routing.module.ts – Defines our app’s routes.

Each Angular component we write will have at a minimum the *.component.ts file, the others are optional. Our application is going to have three components. The main or root component, a component to display the public deals, and a component to display private deals. For our root component, we’ll inline the template and styles. Let’s make the following edits and run the following CLI commands:

Delete app.component.css and app.component.html files. We’ll define all we need for our root component in the app.component.ts file.
Create a public-deals component by running ng g c public-deals –no-spec. This component will take care of getting and displaying the public deals data.
Create a private-deals component by running ng g c private-deals –no-spec. This component will take care of getting and displaying the private deals data.
Create a callback.component.ts file by running ng g c callback –it –is –flat –no-spec.
Create a deal file by running ng g class deal –no-spec. This file will hold our deal class, which will let Angular know the structure of a deal.
Create a deal.service.ts file by running ng g s deal –no-spec. Here we’ll add the functionality to get and retrieve the deal data from our API.

Note: g is a shortcut for generate, and c and s are shortcuts for component and service, respectively. Therefore, ng g c is equivalent to ng generate component. The –no-spec flag indicates that *.spec.ts files should not be generated. The –it and –is flags stand for “inline template” and “inline styles” and –flat indicates that a containing folder should not be created.
Adding HTTP Client Module
We’re going to be making HTTP requests to our API in our Angular app. To do so, we need to add the correct module to our app.module.ts file. Let’s do so now by importing the HttpClientModule and adding it to our @NgModule’s imports array like so:
// app.module.ts

import { HttpClientModule } from ‘@angular/common/http’;

declarations: [

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

Adding Bootstrap CSS
We’re going to use Bootstrap to style our application, so let’s include the CSS in the of our index.html file like so:
<!– src/index.html –>

<link href=”" rel="stylesheet">

Building the Root Component
Every Angular application must have a root component. We can name it whatever we want, but the important thing is that we have one. In our application, the app.component.ts file will be our root component. Let’s take a look at our implementation of this component.
// app.component.ts
import { Component } from ‘@angular/core’;

selector: ‘app-root’,
template: `
<div class="container">
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand" routerLink="/dashboard">{{ title }}</a>
<ul class="nav navbar-nav">
<a routerLink="/deals" routerLinkActive="active">Deals</a>
<a routerLink="/special" routerLinkActive="active">Private Deals</a>
<ul class="nav navbar-nav navbar-right">
<a>Log In</a>
<a>Log Out</a>
<div class="col-sm-12">
styles: [
`.navbar-right { margin-right: 0px !important}`
export class AppComponent {
title = ‘Daily Deals’;

constructor() {}

We’ve created our root component. We added an inline template and some inline styles. We haven’t added all the functionality yet, so every user will be able to see all the links and the login and logout buttons. We’ll wait to implement those a little bit. We’re also displaying the <router-outlet> element. This is where our routed components will show.
Since we initialized our app with the –routing flag, the architecture for routing is already set up for us. Let’s update it so that our Deals component shows by default. We’ll also set up all the routes necessary for our app.
Open the app-routing.module.ts file and add the following:
// app-routing.module.ts
import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { CallbackComponent } from ‘./callback.component’;
import { PublicDealsComponent } from ‘./public-deals/public-deals.component’;
import { PrivateDealsComponent } from ‘./private-deals/private-deals.component’;

const routes: Routes = [
path: ”,
redirectTo: ‘deals’,
pathMatch: ‘full’
path: ‘deals’,
component: PublicDealsComponent
path: ‘special’,
component: PrivateDealsComponent
path: ‘callback’,
component: CallbackComponent

imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
export class AppRoutingModule { }

We can just navigate to localhost:4200 in the browser and see our app displayed. We won’t see much yet, just the top navbar and a message saying that the deals component works.
The Deal Type
TypeScript allows us to define the structure or type of our objects. This serves a bunch of useful purposes. For one, if we define the structure of an object, we’ll be able to get all of the object’s data via IntelliSense. We can additionally test our components easier by knowing the data structure or type of object we are dealing with.
For our app, we’ll create one such type. In the deal.ts file, we’ll define a type of Deal. Let’s see how we’ll accomplish this.
// deal.ts
export class Deal {
id: number;
name: string;
description: string;
originalPrice: number;
salePrice: number;

Now we can declare objects in our Angular application to be a type of deal. These objects will gain all of the properties and methods of the deal type. We’re only defining properties here; we won’t have any methods.
Continue reading %Authentication with Angular and Auth0%


Okta, Auth0, & the Goblet of Identity

I’ve been exploring a couple of different options when it comes to serverless authentication providers, and I was both pleased and surprised to find how little effort was required on my part, and how deep the rabbit hole can go! Being far from a security expert, and having implemented a few different auth systems in my time, I can relate to the challenge of figuring out how to do this on your own. Luckily, there are many SaaS platforms that focus on identity management and authentication, sometimes referred to as IDaaS providers. I recommend using one of these platforms rather than trying to build authentication solutions themselves. Authentication is the process of verifying a user’s identity by logging in with a username, password,and so on. Authorization is the process of verifying that a user has accessto a resource through the use of groups, roles, permissions, and so on. These features, and more, are also offered by these cloud-based IDaaS providers. There are quite a few providers to choose from, but for this article, I’ll focus on two that I’m personally familiar with. The first IDaaS solution we will explore is [Okta][okta], which historically focused on SSO (Single Sign-On) for employees, but have recently created a more developer-focused offering. The second we’re going to review is Auth0, which seems to have always focused on a developer-oriented solution.When IDaaS Providers Make Sense API-driven authentication providers bail us out of the ordeal of having to set up a full-fledged authentication and authorization system on our own. User systems are highly dynamic in that they change frequently, and are also the biggest target for malicious agents. Building our own user system is not only complex and time consuming, but can also lead to security problems now and in the future. By using an IDaaS provider, we can cut down on development time and trouble, while also ensuring our system is built and secured by industry experts. When we’re looking for a simple drop-in solution that allows users to sign up and log into our application in the least amount of time, both Oktaand Auth0 have solutions available. Beyond the simplest use cases, both allow for multiple authentication strategies through an SDK you can customize. Drop-in Authentication Solutions Okta has two drop-in solutions available: their standard sign-in page, which is a hosted redirect authentication solution, and their Sign-in Widget. The sign-in widget allows for a well featured login solution that I found easy to integrate. You can customize the styling, and have something up and running fairly quickly. The Okta Sign-in Widget is easy to add to any web app and can be included with the following code:
<title>Example Okta Sign-In Widget</title>
<script src=’’></script>
<link href=’’ type=’text/css’ rel=’stylesheet’>
<link href=’’ type=’text/css’ rel=’stylesheet’>
<div id=’okta-login-container’></div>
const orgUrl = ‘https://$’
const oktaSignIn = new OktaSignIn({ baseUrl: orgUrl })
oktaSignIn.renderEl({ el: ‘#okta-login-container’ }, function (res) {
if (res.status ===’SUCCESS’) {
Auth0 also has two drop-in solutions available. Firstly, the Lock widget, which is similar to Okta’s sign-in widget, but allows for more customization options,such as the ability to add custom registration fields that will then be saved into the user’s metadata, which is nice. Secondly, theAuth0widget comes with a central login page which allows you to set up a fully-featured user management solution with full interface customization. The Auth0 Lock widget is also really easy to integrate, and can be included with the following code: <html>
<title>Example Okta Sign-In Widget</title>
<script src=’’></script>
const lock = new Auth0Lock(‘$AUTH0_LOCK_SECRET’, ‘’, {
auth: {
redirectUrl: ‘http://localhost:3000/auth/auth0/callback’,
responseType: ‘code’,
params: {
scope: ‘openid email’ // more about scopes:
<button onclick=’’>Login</button>
Okta has 10 quick start guides, while Auth0 has a staggering 56 quick start guides and whole sample applications, both seemingly drowning us in tutorial choices to pick from. Thankfully, these vary by the kind of application we’re building and the language, so the more the merrier! Time to First API Call with Okta The Express sample tutorial for Okta in Node.js was simple enough to run through and didn’t pose any problems. After registering a developer account with Okta and creating a Web application in the admin back-end, I took the Client ID and Secret and placed them into a JSON config file for my application: {
“OKTA_ISSUER": "https://$",
"OKTA_REDIRECT_URL": "http://localhost:8080/authorization-code/callback"
One thing to note about this specific authentication flow with Okta is that they use a stateful user session cookie to store the authorization details. app.use(cookieParser())
secret: ‘AlwaysOn’,
cookie: { maxAge: 3600000 },
resave: false,
saveUninitialized: false

const oidc = new ExpressOIDC({
issuer: sampleConfig.OKTA_ISSUER,
client_id: sampleConfig.OKTA_CLIENT_ID,
client_secret: sampleConfig.OKTA_CLIENT_SECRET,
redirect_uri: sampleConfig.OKTA_REDIRECT_URL,
scope: ‘openid profile email’
With a simple setup and straight-forward tutorial, let’s put the time taken from the start of our trial to the first useful API call being made at roughly 17 minutes. Not bad! Time to First API Call with Auth0 Running through the Node.js quick start tutorial for Auth0 had me drop in their login page on a basic vanilla web application. After signing up for a free Auth0 developer account, I created a Standard Web Client in their management dashboard and copied the Client ID and Domain to my app’s variables: {
"AUTH0_DOMAIN": "$",
"AUTH0_REDIRECT_URL": "http://localhost:3000"
The main code to include the Auth0 Web Auth module is pretty simple, as is storing the authorization details in local storage: const webAuth = new auth0.WebAuth({
domain: sampleConfig.AUTH0_DOMAIN,
clientID: sampleConfig.AUTH0_CLIENT_ID,
redirectUri: location.href,
audience: `https://${ sampleConfig.AUTH0_DOMAIN }/userinfo`,
responseType: ‘token id_token’,
scope: ‘openid’,
leeway: 60

function setSession(authResult) {
const expiresAt = JSON.stringify(
new Date().valueOf() + authResult.expiresIn * 1000

localStorage.setItem(‘access_token’, authResult.accessToken)
localStorage.setItem(‘id_token’, authResult.idToken)
localStorage.setItem(‘expires_at’, expiresAt)
Running the web application, we can see the session details being stored in local storage in the image below. The encoded JWT id_token is highlighted in red. We can also observe the session being destroyed on logout. Overall, the Auth0 time to first useful API call took just under 9 minutes. Yay! Development Experience I also wanted to secure an API back-end that powered a single-page web application and had to figure out what OAuth flow to utilize. The Client Credentials Grant seemed to make the most sense for a back-end API. Both Auth0 and Okta offer multiple OAuth 2.0 authentication flows, including the server-to-server flow required to secure an API back-end. From an API and documentation point of view, both providers are quite nice, and have fairly clear and concise documentation to help you pick the most appropriate flow, aiding with the implementation. In general, though, the Auth0 documentation is a bit nicer, with clear explanations and detailed diagrams. For instance, Auth0 has an entire page of documentation dedicated to choosing an OAuth 2.0 flow. Okta does have a section on choosing flows, but it is a bit less detailed than the Auth0 page. Social Login Integrations Now that I had the API back-end authentication taken care of using the above OAuth2.0 flow, I needed to add social logins to the application. Naturally, both Okta and Auth0 offer social login solutions. Okta offers an extensive Social Login solution which is feature-rich, well documented, and easy to implement. Auth0 also offers an excellent Social Login solution with integrations to many providers, and the extensibility options of adding your own custom providers. In the case of my recent implementation, we required custom social login providers, and the ability to do so with Auth0 was a deal-breaker. With that, I had all of the authentication taken care of… Or so I thought! Multi-Factor Authentication Realizing that we were storing a fair amount of sensitive data in user profiles, and wishing for an extended level of security, we had to implement Multi-Factor Authentication. MFA allows for an additional layer of security, decreasing the likelihood of unauthorized access to user accounts. MFA is widely recommended for full usage across the web. Both providers have multiple options available for the multi-factor auth process, with Okta presenting more configuration settings. I have previously written about setting up 2FA on your own in Node.js, but given I was already going to use an IDaaS solution, it made much more sense to keep all authentication and authorization concerns in a single place. Both providers have the ability to integrate an MFA solution into our applications. Options for Okta include: SMS, Google Authenticator, and several others. Although most cases would be covered here, Okta doesn’t allow for a custom solution to be included. The MFA options for Auth0 include: push notifications (demo), SMS, Google Authenticator, and, crucially: contextual MFA through rules or custom providers. User Management API Lastly, I needed a simple interface to manage users on the web. I built this using user management REST API commands. Auth0 and Okta each provide a Management API for administrative tasks. For instance, if we wish to update a user’s profile through the REST API, we can do so with the following API call with Okta: curl \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: SSWS $API_TOKEN" \
-d ‘{
"profile": {
"firstName": "Vincent",
"lastName": "Adultman",
"email": "",
"login": "",
"mobilePhone": "555-415-1337"
}’ "https://$$USER_ID"
And with Auth0: curl \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d ‘{
"Blocked": false,
"Email_verified": true,
"Email": "",
"profileCode": 1479,
"addresses": {
"work_address": "100 Industrial Way",
"home_address": "742 Evergreen Terrace"
"App_metadata": {},
"Connection": "business-db",
"Username": "vincent_adultman",
"Client_id": "DaM8bokEXBWrTUFCiJjWn50jei6ardyX"
}’ "$USER_ID"
Both API calls are similar, although Auth0 provides better handling of custom profile fields, allowing these to be created and modified on the fly. With Okta, custom profile fields can only be specified if first created through either the Admin UI, or the Schemas API, as per the Okta documentation: User profiles may be extended with custom properties but the property must first be added to the user profile schema before it can be referenced. You can use the Profile Editor in the Admin UI or the Schemas API to manage schema extensions. Although you must first define profile fields, this does lead to an advantage where Okta allows for granular event logging and tracking. You can access analytics on a profile attribute level, which is useful in scenarios when you must have a log of every change made to individual fields at any time, such as for a financial, or gambling application. Auth0 cannot track updates at this level as their user profile objects have a flexible schema. One other point to note with Okta here is the usage of the PUT HTTP verb when updating a user profile. If you were to use the PUT verb, any unspecified properties would be overridden with null values. From the Okta docs: Note: Use the POST method to make a partial update and the PUT method to delete unspecified properties. As far as I’m concerned this is a pretty weird API to offer, since virtually nobody would expect this behavior, and it may lead to data loss if we don’t test properly and mistakenly use PUT thinking it’d just update the provided fields. Extensibility Okta has a large list of extensions and integrations. They also include the ability to create your own integrations, albeit the options are slightly limited. You can read up on how to create Okta integrations here. Auth0 has a strong focus on extensibility and offers a platform on which to build extensions and integrations beyond just webhooks: Auth0 Extend. With a focus on a serverless back-end, Extend helps create and deploy extensions in very little time. The extensibility Auth0 provides was a blessing, as was using Webtask as a modern replacement for cron jobs. OpenID and SAML OpenID Connect (OIDC) is an authentication protocol based on the OAuth 2.0 family of specifications. It uses simple JWT tokens delivered via the OAuth protocol, and its purpose is to enable you to use one login across multiple sites. Again, both providers offer a solution for this, ultimately receiving authorization requests and sending back ID and access tokens. To get started with Okta’s OIDC solution, check their documentation here. To get started with Auth0’s OIDC solution, read their documentation here. Both providers have similar solutions in terms of both functionality and usage. Both Okta and Auth0 offer integrations for SAML as well. Both platforms can be used as both your Service Provider and your Identity Provider. Although both platforms offer similar solutions for this scenario, Auth0 has fewer options in their catalog. Okta has a lot more SAML integration options available, and therefore are the choice provider for this scenario. Okta also offers a SAML testing tool, which is pretty nifty. That being said, I did find it easier to navigate the Auth0 resources for information on SAML. Auth0 has extensive SAML documentation whereas Okta has a more sparse SAML documentation. Documentation and Resources The first step when researching a new product is usually reading its documentation. This leaves API providers with a distinct need to provide excellent, detailed, and concise documentation. One of the first features of both providers’ documentation I would like to mention is the ability with both to export the API documentation to the Postman REST Client. Both Okta and Auth0 allow developers to test out the API functionality in real-time by installing preset collections in Postman. With Okta, you can get an overview of the Postman testing integration. For Auth0, you can read about using the Auth0 API with Postman. Both the Okta and Auth0 API reference documentations are pretty comprehensive. One of the best examples of good API documentation belongs to Stripe, the payment API provider. While Auth0does provide copy/paste samples in a few formats and Oktadon’t really do that, Stripe has nailed the concept, allowing developers to find snippets of API calls that they can copy directly in a multitude of languages, and which actually work without the need for any modifications whatsoever. Conclusion I set out to explore the functionality of two of the leading IDaaS solutions, and in the process I’ve also gained a deeper understanding of how both services work and what they offer. It’s clear to me that Auth0 is the more developer-friendly choice, with gorgeous design around their products, which is always something the front-end developer in me seeks and naturally gravitates towards. The Auth0 offering was clearly conceived from scratch to support a wide range of scenarios and use cases, while Okta made me work harder to get integrations going. Overall, both solutions mostly get the job done, but I prefer Auth0 for its elegance and simplicity, if not completeness.


Easily Migrate Your Existing Users to Auth0

User migration is a dreaded, sometimes unavoidable task that is difficult for developers, inconvenient for users, and expensive for business owners. The need for migrating users from one service or platform to another can stem from any number of reasons: the identity provider you are currently using is shutting down, your organization no longer wishes to manage users themselves, a change in language or framework, and many other reasons.
Auth0 aims to provide the best authentication and identity management platform that is simple and easy for developers to work with. A key feature of the Auth0 platform is the ability to migrate users from any existing data source into Auth0 without inconveniencing users by requiring password changes.
In this tutorial, we’ll take a look at how to do just that. Stormpath is a company that provides authentication as a service and was recently acquired by Okta. Okta has announced that the Stormpath product will be shut down in August 2017 and customers have until then to find a new provider. Let’s see how we can easily migrate existing Stormpath users into Auth0.
User Migration Made Easy with Auth0
Auth0 allows customers to connect to any custom datastore using the custom database connection feature. This feature, as the name may suggest, allows Auth0 to validate user credentials that are stored outside of Auth0. The external data store can be a database such as MySQL, a service like Stormpath, or your own custom implementation. These external data sources are accessed via scripts written in the Auth0 dashboard. The custom database connection feature also allows developers to automatically import users logging in with custom database credentials into Auth0. This feature can be enabled with the flip of a switch.
To implement this feature in the context of migrating Stormpath users to Auth0, we’ll set up a custom database connection and connect it to an existing Stormpath account using the Stormpath API. When your users log in the first time, they will enter their existing Stormpath credentials and, if authenticated successfully, we will automatically migrate that user account from Stormpath into Auth0. Your users will not have to change their password or jump through any additional hoops and you can decide what data to port over from Stormpath. The next time the user logs in, Auth0 will detect that they have been migrated and authenticate them with their Auth0 account.

To get started, first sign up for a free Auth0 account. We’ll assume that you already have an active Stormpath account with users you wish to migrate. Even if you are not using Stormpath, you can follow along with this tutorial and connect to a different datastore.
Setting up a Custom Database Connection with User Import Functionality
With your account created, let’s set up a custom database connection. In your Auth0 management dashboard, navigate to the database connections section.

Click on the Create DB Connection button to create a new database connection. You can name your connection anything you like. Leave all the default settings as is for now and click the Create button to create the connection.

Next, let’s go into this database connection and connect it to our Stormpath account. Click on your newly created connection and navigate to the Custom Database tab. Flip the switch titled “Use my own database" and the Database Action Scripts section will now be enabled. This is where we will write our code to connect to your existing Stormpath user datastore.
We will need to write two scripts: Login and Get User. Login will proxy the login process and Get User will manage looking up accounts when a user attempts to reset their password.

With our custom database feature turned on, let’s enable the import functionality. By default, the custom database connection will allow us to authenticate with an external database and will not import users to Auth0. If we want to migrate users from the external platform into Auth0 we’ll need to simply toggle a switch. Go to the Settings tab of the connection and flip the switch titled "Import Users to Auth0" and you’re done.

One final step we’ll do before implementing our scripts is enabling this connection for our default client. Navigate to the Clients tab while you are in your database connection and flip the switch to enable this client for the Default Connection. If you already have an existing Auth0 account, the connection name may be different.

The Login script is executed when a user attempts to sign in but their account is not found in the Auth0 database. Here we will implement the functionality to pass the user credentials provided to our Stormpath user data store and see if that user is valid. Auth0 provides templates for many common databases such as MongoDB, MySQL and SQL Server, as well as Stormpath. These templates provide a great starting point and you can customize them any way you want or write your own from scratch.
The Database Action Scripts run in a Webtask sandbox and are Node.js scripts. As our tutorial is focused on migrating Stormpath users to Auth0, the scripts shown below will be geared towards working with the Stormpath REST API, but if you are migrating users from a different provider, you would write your implementation here or use one of the other templates provided.
Let’s look at the Login script implementation to see how it works. We will utilize Stormpath’s REST API to authenticate the user.
function login(username, password, callback) {
// Replace the YOUR-STORMPATH-CLIENT-ID with your Stormpath ID
var url = ‘{YOUR-STORMPATH-CLIENT-ID}/loginAttempts’;
// Add your Stormpath API Client ID and Secret
var apiCredentials = {

// Stormpath requires the user credentials be passed in as a base64 encoded message
var credentials = new Buffer(username + ‘:’ + password).toString(‘base64’);

// Make a POST request to authenticate a user
url: url,
method: ‘POST’,
auth: apiCredentials,
json: {
type: ‘basic’,
// Passing in the base64 encoded credentials
value: credentials
}, function (error, response, body) {
// If response is successful we’ll continue
if (response.statusCode !== 200) return callback();
// A successful response will return a URL to get the user information
var accountUrl = body.account.href;

// Make a second request to get the user info.
url: accountUrl,
auth: apiCredentials,
json: true
}, function (errorUserInfo, responseUserInfo, bodyUserInfo) {
// If we get a successful response, we’ll process it
if (responseUserInfo.statusCode !== 200) return callback();

// To get the user identifier, we’ll strip out the Stormpath API
var id = bodyUserInfo.href.replace(‘’, ”);

// Finally, we’ll set the data we want to store in Auth0 and migrate the user
return callback(null, {
user_id : id,
username: bodyUserInfo.username,
// We set the users email_verified to true as we assume if they were a valid
// user in Stormpath, they have already verified their email
// If this field is not set, the user will get an email asking them to verify
// their account. You can decide how to handle this for your use case
email_verified: true
// Add any additional fields you would like to carry over from Stormpath

Continue reading %Easily Migrate Your Existing Users to Auth0%