Over a million developers have joined DZone.

Angular 2 Authentication Tutorial: Part I

In this tutorial we are going to look at how to build applications with Angular 2 as well as how to add token based authentication to Angular 2 apps the right way.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Angular 2.0 has finally been released. In this tutorial we are going to look at how to build applications with Angular 2 as well as how to add token based authentication to Angular 2 apps the right way. Check out the completed code example from our GitHub repo.

Angular 2 finally hit the major 2.0 release milestone just a few weeks ago. The final release of Angular 2 did not have many breaking changes. The Release Candidate 5 (RC5) release, made available just a few weeks prior to final, introduced major breaking changes and additions such as the @NgModule decorator, Ahead-of-Time (AOT) compiler and more.

In today's tutorial, we are going to utilize some of these new features to build an entire Angular 2 application. Components, @NgModule, route guards, services, and more are just some of the topics we'll touch on. Finally, we'll implement token based authentication with Auth0.

The Angular 2 Ecosystem

Angular 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 Angular 1.x is a framework, Angular 2 is an entire platform for building modern applications. Alongside the core Angular 2 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 Universal brings server-side rendering to Angular 2 applications.Angular Material 2 is the official implementation of Google Material Design which allows developers to build beautiful applications with ease.

Angular 2.0 has officially shipped, but the other components of the platform are still in alpha and beta stages. For our application today, we will make use of the Angular CLI and the core Angular 2 framework, but we'll let the other components bake a little longer.

"While Angular 1 is a framework, Angular 2 is an entire platform for building modern applications"

Our App: Daily Deals

Daily Deals App

The app we are 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 backend 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');


// 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 2 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 are happy with the public and private deals, launch the server by running node server and navigate to bothlocalhost:3001/api/deals/public and localhost:3001/api/deals/privateto make sure you can see the list of deals you added. Next, let's set up our Angular 2 front-end.

Angular 2 Front-End Setup

One of the best ways to start building a new Angular 2 app is with the official Angular 2 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 will scaffold our initial app with the CLI.

If you don't already have it installed, run npm install angular-cli -g to install the Angular CLI. We'll interact with the CLI using the ng command. To create a new application, choose a directory and run ng init. This will create a new Angular 2 application in selected directory, download all of the required NPM packages, and basically set everything up for us.

Once ng init is finished, 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 servecommand 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 are golden. Next, let's examine how our Angular 2 app is scaffolded.

The ng init command scaffolded our Angular 2 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 theapp directory.

The app directory contains the bulk of our application. By default we are 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.spec - // Holds the tests for our root component
- app.component.ts - // Holds the TypeScript logic for our root component
- app.module.ts - // Defines our global app dependencies
- index.ts - // Exports our application
- shared - // This directory holds any shared components we may have

Each Angular 2 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 we won't write any tests so let's make the following edits:

  • Delete app.component.css, app.component.html andapp.component.spec files. We'll define all we need for our root component in the app.component.ts file.
  • Create a public-deals.component.ts, public-deals.component.html, andpublic-deals.component.css file. This component will take care of getting and displaying the public deals data.
  • Create a private-deals.component.ts, private-deals.component.html, and private-deals.component.css file. This component will take care of getting and displaying the private deals data.
  • Create a deal.ts file. This component will hold our deal class which will let Angular 2 know the structure of a deal.
  • Create a deal.service.ts file. Here we'll add the functionality to get and retrieve the deal data from our API.
  • Finally, create an app.routing.ts file which will take care of our routes.

Building the Root Component

Every Angular 2 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.

// Import the Component decorator
import { Component } from '@angular/core';

  // We'll call our root component daily-deals
  selector: 'daily-deals',
  template: `
  <div class="container">
    <nav class="navbar navbar-default">
        <div class="navbar-header">
          <a class="navbar-brand" routerLink="/dashboard"></a>
        <!-- On the left side of our navbar we'll display the two links for public and private deals -->
        <ul class="nav navbar-nav">
            <a routerLink="/deals" routerLinkActive="active">Deals</a>
            <a routerLink="/special" routerLinkActive="active">Private Deals</a>
        <!-- On the right side of our navbar we'll display the login and logout actions depending on user state -->
        <ul class="nav navbar-nav navbar-right">
            <a>Log In</a>
            <a>Log Out</a>
    <div class="col-sm-12">
      <!-- The router-outlet directive will display the component based on the route we are on, more on this soon -->
  // We'll add an inline style to properly display the navbar
  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.

To use this component, open the index.html file in your directory and replace<my-app></my-app> with <daily-deals></daily-deals>. We left the class name AppComponent so we don't need to make any edits to our app.module.tsfile. We can just navigate to localhost:4200 and see our app displayed. We won't see much yet, just the top navbar.

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.

export class Deal {
  id: number;
  name: string;
  description: string;
  originalPrice: number;
  salePrice: number;

Now we can declare objects in our Angular 2 application to be a type of deal. These objects will gain all of the properties and methods of the deal type. We are only defining properties here, we won't have any methods.

Public and Private Deals Components

The public and private deals components are very similar. In fact, the only difference between the two implementations is that one will display deals from the public API and the other will display deals from the private API. For posterity, we'll just show one of the component implementations. Let's implement the public-deals.component.ts.

import { Component, OnInit } from '@angular/core';
import { Deal } from './deal';
// We haven't defined these services yet
import { AuthService } from './auth.service';
import { DealService } from './deal.service';

  selector: 'public-deals',
  // We'll use an external file for both the CSS styles and HTML view
  templateUrl: 'public-deals.component.html',
  styleUrls: ['public-deals.component.css']
export class PublicDealsComponent implements OnInit {
  publicDeals: Deal[];

  // Note: We haven't implemented the Deal or Auth Services yet.
    private dealService: DealService,
    private authService: AuthService) {
  // When this component is loaded, we'll call the dealService and get our public deals.
  ngOnInit(): void {
      .then(deals => this.publicDeals = deals);

    alert("You bought the: " + item.name);

Next, let's build the view of our public deals component. We'll do this in thepublic-deals.component.html file. Our view will be a mixture of HTML and Angular 2 sugar. Let's take a look at our implementation.

  <h3 class="text-center">Daily Deals</h3>

  <!-- We are going to get an array of deals stored in the publicDeals variable. We'll loop over that variable here using the ngFor directive -->
  <div class="col-sm-4" *ngFor="let deal of publicDeals">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title"></h3>
      <div class="panel-body">

      <div class="panel-footer">
        <ul class="list-inline">
          <li class="pull-right">Sale</li>
        <ul class="list-inline">
          <li><a class="btn btn-danger">$</a></li>
          <li class="pull-right"><a class="btn btn-success">$</a></li>

  <!-- We are going to use the authService.loggedIn() method to see if the user is logged in or not. If they are not logged in we'll encourage them to login, otherwise if they are logged in, we'll provide a handy link to private deals. We haven't implemented the authService yet, so don't worry about the functionality just yet -->
  <div class="col-sm-12" *ngIf="!authService.loggedIn()">
    <div class="jumbotron text-center">
      <h2>Get More Deals By Logging In</h2>

  <div class="col-sm-12" *ngIf="authService.loggedIn()">
    <div class="jumbotron text-center">
      <h2>View Private Deals</h2>
      <a class="btn btn-lg btn-success" routerLink="/special">Private Deals</a>

Finally, let's add a custom style. In the public-deals.component.css file add the following:

.panel-body {
    min-height: 100px;

This will ensure that each of the products displays nicely on our page.

Our private deals component will look very similar. For posterity, we won't display the scaffold. We'll cover the changes a little later on. If you'd like to see what it looks like, you can view it from our GitHub repo.

Accessing Our Deals API

Earlier in the tutorial, we wrote a very simple API that exposed two routes. Now, let's write an Angular 2 service that will interact with these two endpoints. We'll do this in the deal.service.ts file. The implementation is as follows:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Deal } from './deal';

export class DealService {
  // Define the routes we are going to interact with
  private publicDealsUrl = 'http://localhost:3001/api/deals/public';
  private privateDealsUrl = 'http://localhost:3001/api/deals/private';

  constructor(private http: Http) { }

  // Implement a method to get the public deals
  getPublicDeals() {
    return this.http
      .then(response=>response.json() as Deal[])

  // Implement a method to get the private deals
  getPrivateDeals() {
    return this.http
      .then(response=>response.json() as Deal[])

  // Implement a method to handle errors if any
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);

Now you can see where the getPublicDeals() method fits in from our public-deals.component.ts file. We also have written a getPrivateDeals() method that will get our list of private deals. Implement this method in your private-deals.component.ts file.

Implementing the Routes

Now that we have our two components created, let's implement routing so that we can display the appropriate component. Routing in Angular 2 has changed a couple of different times. The new new new router is really great though and supports many features developers have been asking for such as lazy loading.

For our application, we will create two routes. The /deals route will display the publically available deals, and the /special route will display the exclusive private deals that only registered users will have access to. We'll also add a redirect, so that when the user lands on the homepage, we'll automatically redirect them to the deals page. Let's see how we are going to implement this.

import { Routes, RouterModule} from '@angular/router';

// Import our components
import { PublicDealsComponent } from './public-deals.component';
import { PrivateDealsComponent } from './private-deals.component';

const appRoutes: Routes = [
  // Add the redirect
    path: '',
    redirectTo: '/deals',
    pathMatch: 'full'
  // Add our routes
    path: 'deals',
    component: PublicDealsComponent
    path: 'special',
    component: PrivateDealsComponent
// Here we are exporting our routes
export const routing = RouterModule.forRoot(appRoutes);
// Here we are combining our routing components into a single array. We will use this a little later when we update our root module
export const routedComponents = [PublicDealsComponent, PrivateDealsComponent];

Our routing is looking good. Our entire application should be ready to test now. Before we test our application, there is one final thing we need to do to ensure that everything works correctly. Note: If you decide to test your application before the conclusion of the tutorial, you will need to remove the AuthService from your deals components, otherwise Angular will complain.

We need to update our root @NgModule to include all of the new components and services we've written. To do this, open the app.module.ts file. In this file, you'll see the root module that the Angular bootstrap created for us. We are going to edit it as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

// Import our dependencies
import { AppComponent } from './app.component';
import { routing, routedComponents } from './app.routing';

import { DealService } from './deal.service';

  imports: [
    // Include the routing module
  declarations: [
    // Include our array of routing components. This saves us from having to type out the entire list of components twice
  providers: [
    // Add our deal service we created earlier
  // Declare our root component, which is the AppComponent
  bootstrap: [AppComponent]
export class AppModule { }

Now we are ready to test our app. If you would like more information on how @NgModule works, check out this post. Navigate to localhost:4200 and you should see be redirected to the deals page automatically. Notice that you can freely navigate to the /secret route and see the exclusive deals as well. You can do this because we haven't added user authentication yet. Let's do that next.

Stay tuned for Part II, coming soon!

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

angular 2,tokens,authentication,web dev

Published at DZone with permission of Ado Kukic, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}