{{announcement.body}}
{{announcement.title}}

Authenticate Your Angular App With JWTs

DZone 's Guide to

Authenticate Your Angular App With JWTs

In this article, we discuss how to use JWTs and an Angular client to add user authentication to your Node and Express application.

· Security Zone ·
Free Resource

No web application should ever be made without a user registration and authentication feature. Authentication gives permission for a user to access the proper resources or services. The fundamental property of HTTP is a stateless protocol that contradicts authentication, which works to keep the state of the user. 

JSON Web Tokens (JWTs) help get around the contradiction between HTTP and authentication. The backend of the Angular app authenticates the JWT, validates the user, and grants them access. To make this happen, the app talks to the backend to generate a token, which then is communicated to the Authorization header to verify the token. You can also address this issue with session-based authentication and cookies. This means that the backend will create a “session cookie,” which provides a process for the server to confirm the user’s identity. 

Session vs JWT Authentication in Angular

If you’re like me, you have been developing for the web for some time. You might have come across different ways of resolving this problem. The traditional approach uses sessions to keep the state. When a user visits a website and logs in, the server will store the authentication state in a session.

It then returns a unique session ID to the client, which is usually stored in a browser cookie. Every time the client makes a request to the server, the cookie is sent in the request header, and the server can look up the session data from the session ID. While this approach has been applied successfully for many years, it has some drawbacks.

Session-based authentication relies on session data being stored on the server. The server that authenticates the user must be the same server that checks the authentication and provides the service. Imagine a web service that is deployed on multiple servers and sits behind a load balancer or reverse proxy. Each request that a client makes could end up being handled by a different server. The session data would then have to be shared among all servers. This would undo most of the improvement introduced by the load balancer.

Another downside of session-based authentication is the increased usage of single sign-on services. Here, the user signs on once with a central authentication service. After that, the user can freely use any server that trusts the authentication service. This can not only be useful when registering with websites using Google or Facebook accounts.

Increasingly, businesses organize their workflows with a large number of separate tools. Using a single sign-on, employees will register once and are then able to use all tools without further authentication. It would be highly impractical to implement single sign-on using sessions because the different applications would have to communicate with each other and exchange their private session data.

You may also like: How JSON Web Token (JWT) Secures Your API.

JWTs to the Rescue for Angular Authentication

Because of the problems outlined above, services are increasingly using JSON Web Tokens (JWT) to implement authentication. With JWT authentication, there is no need for the server to store any session data. The server can be truly stateless. So how does this work?

When a user logs into a service, the server checks the user’s credentials. If successful, the server encodes the key user data, such as a user ID or the user’s email address into a JSON string. The string is then signed using a secret key. This data is the JSON Web Token. It can be sent back to the client and used by the client to authenticate itself.

If a server can validate the token with the appropriate key, it can be sure that it was generated by the authentication server. But it can’t be forged because only the authentication server knows the private key. The authentication can be provided by a service that is separate from the service wanting to restrict access.

Implement a JWT Server and Client with Node and Angular

In this section, I will show you how to implement JWT authentication using a Node and Express server with a client written with Angular. You will see that, even though the concept is simple, the implementation requires knowledge of security best practices. The example given here is not complete and lacks a number of features required by a production server. In the next section, I will show you that Okta provides a simple and elegant solution to these shortcomings.

I will assume that you have some knowledge of JavaScript and that you have installed Node and the npm command line tool on your server.

Build a JWT Authentication Server

To start implementing the server that authenticates users using JSON Web Tokens, open a terminal and create a directory that will contain the server application, I have called my directory jwt-server. Navigate into that directory and run the following command to initialize your project.

Shell




x


 
1
npm init -y



You will need a number of packages to implement the server. Install then by running this command.

Shell




xxxxxxxxxx
1


 
1
npm install --E cors@2.8.5 nodemon@1.18.10 bcryptjs@2.4.3 sqlite3@4.0.6 njwt@1.0.0 \
2
  express@4.16.4 body-parser@1.18.3 express-bearer-token@2.2.0



I will explain each of these libraries when they appear in the code. Open up your favorite text editor and create a new file index.js with the following content.

JavaScript




xxxxxxxxxx
1
18


 
1
const express = require('express');
2
const cors = require('cors');
3
const bodyParser = require('body-parser');
4
const bearerToken = require('express-bearer-token');
5
const profile = require('./profile');
6
 
          
7
const port = process.env.PORT || 10101;
8
 
          
9
const app = express()
10
  .use(cors())
11
  .use(bodyParser.json())
12
  .use(bearerToken());
13
 
          
14
app.use('/', profile);
15
 
          
16
app.listen(port, () => {
17
  console.log(`Express server listening on port ${port}`);
18
});



This is the main server application. It first creates an express server that is used to listen to incoming HTTP requests and lets you register callback functions that generate responses to those requests. The server uses a number of middlewares that extend the behavior of the express server. The cors middleware allows the server to respond to Cross-Origin Requests. Body-parser is needed to parse the HTTP request body and create an object that is attached to the request data. Similarly, express-bearer-token extracts a bearer token from the request header and makes it available through the request object.

The express application attaches a router to the main route /. This router is defined in a separate file called profile.js. The first route that you will be implementing in this file lets a user register an account.

JavaScript




xxxxxxxxxx
1
25


 
1
const express = require('express');
2
const bcrypt = require('bcryptjs');
3
const sqlite3 = require('sqlite3').verbose();
4
 
          
5
const db = new sqlite3.Database(':memory:');
6
 
          
7
db.serialize(() => {
8
  db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, password TEXT)");
9
});
10
 
          
11
const router = express.Router();
12
 
          
13
router.post('/register', function(req, res) {
14
  var hashedPassword = bcrypt.hashSync(req.body.password, 8);
15
 
          
16
  db.run("INSERT INTO users (name, email, password) "
17
        + "VALUES (?, ?, ?)", req.body.name, req.body.email, hashedPassword,
18
  function (err) {
19
    if (err) return res.status(500).send("An error occurred during registration");
20
 
          
21
    res.status(200).send({ status: 'ok' });
22
  });
23
});
24
 
          
25
module.exports = router;



I am using sqlite3 to simulate a user database. In this example, the database is purely held in memory. This means that all data will be lost when the server is stopped. In a production server, you should replace this with a proper SQL or NoSQL database.

When a user registers, their password is hashed using the bcryptjs library. Only the hashed password is stored in the database. On success, the server responds with an ok status. Once a user is registered they need to be able to log on. This can be done in a separate route /login. This is where you will start using JSON Web Tokens. Before you start implementing, create a file config.js that will store the secret for creating web tokens.

JavaScript




xxxxxxxxxx
1


 
1
module.exports = {
2
  'secret': 'my_special_secret'
3
};



Next, add the require statement for njwt and the new config.js to profile.js.

JavaScript




xxxxxxxxxx
1


 
1
const nJwt = require('njwt');
2
const config = require('./config');



Then, create the /login route in the same file.

JavaScript




xxxxxxxxxx
1
16


 
1
router.post('/login', function(req, res) {
2
  db.get("SELECT id, name, email, password FROM users " 
3
        + "WHERE email=?", req.body.email, function (err, user) {
4
    if (err) return res.status(500).send({status: 'Server error', err:err});
5
    if (!user) return res.status(404).send('User not found');
6
 
          
7
    if (!bcrypt.compareSync(req.body.password, user.password)) {
8
      return res.status(401).send({ auth: false, token: null });
9
    }
10
 
          
11
    var jwt = nJwt.create({ id: user.id }, config.secret);
12
    jwt.setExpiration(new Date().getTime() + (24*60*60*1000));
13
 
          
14
    res.status(200).send({ auth: true, token: jwt.compact() });
15
  });
16
});



This route expects two parameters, email and password. The first step is to search in the database for the user’s email and obtain the user’s record. Then, bcrypt is used to compare the user’s password to the hashed password. If successful, a jwt is used to create a token that stores the user’s ID. The token is then sent back to the client in the response.

When a client attempts to access a restricted resource, it needs to send the token in the request header. The server then needs to authenticate the token. You can write an express middleware that performs this authentication task. Create a new file auth.js with the following content.

JavaScript




xxxxxxxxxx
1
18


 
1
const nJwt = require('njwt');
2
var config = require('./config');
3
 
          
4
function jwtAuth(req, res, next) {
5
  if (!req.token) {
6
    return res.status(403).send({ auth: false, message: 'No token provided' });
7
  }
8
 
          
9
  nJwt.verify(req.token, config.secret, function(err, decoded) {
10
    if (err) {
11
      return res.status(500).send({ auth: false, message: 'Could not authenticate token' });
12
    }
13
    req.userId = decoded.body.id;
14
    next();
15
  });
16
}
17
 
          
18
module.exports = jwtAuth;



Remember the express-bearer-token middleware which extracts the JWT token from the request and places makes it available through req.tokenjwt.verify is used to check whether the token is valid or not. This function also extracts the user ID that was stored in the token and allows you to attach it to the request object.

All this now allows you to create a route that is protected and only available to users that are logged in. Open profile.js again and add the following.

JavaScript




xxxxxxxxxx
1
13


 
1
const jwtAuth = require('./auth');
2
 
          
3
router.get('/profile', jwtAuth, function(req, res, next) {
4
  db.get("SELECT id, name, email FROM users WHERE id=?", req.userId, function (err, user) {
5
    if (err) {
6
      return res.status(500).send("There was a problem finding the user.");
7
    }
8
    if (!user) {
9
      return res.status(404).send("No user found.");
10
    }
11
    res.status(200).send(user);
12
  });
13
});



The /profile route simply returns the user’s profile information. See how the jwtAuth function is added to the /profile route as middleware. This protects the route. It also allows the handler callback to use the req.userId property to look up the user from the database. To test the server, add the following line to the scripts section of package.json.

JSON




xxxxxxxxxx
1


 
1
 "start": "nodemon server.js"



You can now run the server with this command.

Shell




xxxxxxxxxx
1


 
1
npm start



This concludes the simple example of a server that uses JSON Web Tokens for authentication. Next, it is time to implement a client that accesses this server.

Add an Angular Client With JWT Authentication

I will be using Angular to implement the client. First, make sure you have the latest version of the Angular command line tool installed. You might have to run the following command using sudo, depending on your system.

Shell




xxxxxxxxxx
1


 
1
npm install -g @angular/cli@7.3.6



Navigate to a directory of your choice and create a new project for the client.

Shell




xxxxxxxxxx
1


 
1
ng new jwt-client --routing --style=css     



Navigate into this folder and install the libraries for the Foundation responsive CSS framework.

Shell




xxxxxxxxxx
1


 
1
npm install -E foundation-sites@6.5.3 ngx-foundation@1.0.8



Open src/styles.css and paste in the imports for the Foundation styles.

CSS




xxxxxxxxxx
1


 
1
@import '~foundation-sites/dist/css/foundation.min.css';
2
@import '~ngx-foundation/dist/css/ngx-foundation.min.css';



Start by creating a service for communicating with the Node/Express server.

Shell




xxxxxxxxxx
1


 
1
ng generate service server



Open the file src/app/server.service.ts and replace its contents with the following code.

TypeScript




xxxxxxxxxx
1
51


 
1
import { Injectable } from '@angular/core';
2
import { HttpClient, HttpParams } from '@angular/common/http';
3
 
          
4
const baseUrl = 'http://localhost:10101';
5
 
          
6
@Injectable({
7
  providedIn: 'root'
8
})
9
export class ServerService {
10
  private loggedIn = false;
11
  private token: string;
12
 
          
13
  constructor(private http: HttpClient) {}
14
 
          
15
  setLoggedIn(loggedIn: boolean, token?: string) {
16
    this.loggedIn = loggedIn;
17
    this.token = token;
18
  }
19
 
          
20
  request(method: string, route: string, data?: any) {
21
    if (method === 'GET') {
22
      return this.get(route, data);
23
    }
24
 
          
25
    const header = (this.loggedIn) ? { Authorization: `Bearer ${this.token}` } : undefined;
26
 
          
27
    return this.http.request(method, baseUrl + route, {
28
      body: data,
29
      responseType: 'json',
30
      observe: 'body',
31
      headers: header
32
    });
33
  }
34
 
          
35
  get(route: string, data?: any) {
36
    const header = (this.loggedIn) ? { Authorization: `Bearer ${this.token}` } : undefined;
37
 
          
38
    let params = new HttpParams();
39
    if (data !== undefined) {
40
      Object.getOwnPropertyNames(data).forEach(key => {
41
        params = params.set(key, data[key]);
42
      });
43
    }
44
 
          
45
    return this.http.get(baseUrl + route, {
46
      responseType: 'json',
47
      headers: header,
48
      params
49
    });
50
  }
51
}



This service provides functions for posting requests to the server and obtaining the data. One important task of this service is to store the JWT token and add it to the request header. Another service will be in charge of authenticating with the server and obtaining the token. Create this service using the command line.

Shell




xxxxxxxxxx
1


 
1
ng generate service auth



Fill the newly generated file src/app/auth.service.ts with this code.

TypeScript




xxxxxxxxxx
1
55


 
1
import { Injectable } from '@angular/core';
2
import { Router } from '@angular/router';
3
import { BehaviorSubject } from 'rxjs';
4
import { ServerService } from './server.service';
5
 
          
6
@Injectable()
7
export class AuthService {
8
  private loggedIn = new BehaviorSubject<boolean>(false);
9
  private token: string;
10
 
          
11
  get isLoggedIn() {
12
    return this.loggedIn.asObservable();
13
  }
14
 
          
15
  constructor(private router: Router, private server: ServerService) {
16
    console.log('Auth Service');
17
    const userData = localStorage.getItem('user');
18
    if (userData) {
19
      console.log('Logged in from memory');
20
      const user = JSON.parse(userData);
21
      this.token = user.token;
22
      this.server.setLoggedIn(true, this.token);
23
      this.loggedIn.next(true);
24
    }
25
  }
26
 
          
27
  login(user) {
28
    if (user.email !== '' && user.password !== '' ) {
29
      return this.server.request('POST', '/login', {
30
        email: user.email,
31
        password: user.password
32
      }).subscribe((response: any) => {
33
        if (response.auth === true && response.token !== undefined) {
34
          this.token = response.token;
35
          this.server.setLoggedIn(true, this.token);
36
          this.loggedIn.next(true);
37
          const userData = {
38
            token: this.token,
39
          };
40
          localStorage.setItem('user', JSON.stringify(userData));
41
          this.router.navigateByUrl('/profile');
42
        }
43
      });
44
    }
45
  }
46
 
          
47
  logout() {
48
    this.server.setLoggedIn(false);
49
    delete this.token;
50
 
          
51
    this.loggedIn.next(false);
52
    localStorage.clear();
53
    this.router.navigate(['/']);
54
  }
55
}



This service takes care of authenticating the user and, when successful, storing the token in the browser’s local storage as well as notifying the ServerService of the token. You can now use AuthService in your application component. Open src/app/app.component.ts and paste the following content.

TypeScript




xxxxxxxxxx
1
17


 
1
import { Component } from '@angular/core';
2
import { AuthService } from './auth.service';
3
 
          
4
@Component({
5
  selector: 'app-root',
6
  templateUrl: './app.component.html',
7
  styleUrls: ['./app.component.css']
8
})
9
export class AppComponent {
10
  title = 'jwt-client';
11
 
          
12
  constructor(private authService: AuthService) {}
13
 
          
14
  onLogout() {
15
    this.authService.logout();
16
  }
17
}



Change the application component in src/app/app.component.html to contain a top bar that is only visible when the user is logged in.

HTML




xxxxxxxxxx
1
13


 
1
<div class="top-bar" *ngIf="authService.isLoggedIn | async as isLoggedIn">
2
  <div class="top-bar-left">
3
    <a class="logo" routerLink="/">MyApp</a>
4
  </div>
5
  <div class="top-bar-right show-for-medium">
6
    <ul class="menu">
7
      <li><a  routerLink="/profile">Profile</a></li>
8
      <li><a (click)="onLogout()">Logout</a></li>
9
    </ul>
10
  </div>
11
</div>
12
 
          
13
<router-outlet></router-outlet>



Next, create a component that allows a user to register a new user.

Shell




xxxxxxxxxx
1


 
1
ng generate component register



Open src/app/register/register.component.ts and create a component that contains a registration form that can be submitted to the server.

TypeScript




xxxxxxxxxx
1
46


 
1
import { Component, OnInit } from '@angular/core';
2
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
3
import { Router } from '@angular/router';
4
import { ServerService } from '../server.service';
5
 
          
6
@Component({
7
  selector: 'app-login',
8
  templateUrl: './register.component.html',
9
  styleUrls: ['./register.component.css']
10
})
11
export class RegisterComponent implements OnInit {
12
  form: FormGroup;
13
 
          
14
  constructor(
15
    private fb: FormBuilder,
16
    private server: ServerService,
17
    private router: Router
18
  ) {}
19
 
          
20
  ngOnInit() {
21
    this.form = this.fb.group({
22
      email: ['', Validators.email],
23
      name: ['', Validators.required],
24
      password: ['', Validators.compose([Validators.required, Validators.minLength(8)])]
25
    },);
26
  }
27
 
          
28
  onSubmit() {
29
    console.log('Submitting');
30
    if (!this.form.valid) {
31
      console.log('Form not valid. Please check that fields are correctly filled in');
32
      return;
33
    }
34
 
          
35
    console.log('Form valid');
36
    const request = this.server.request('POST', '/register', {
37
      email: this.form.get('email').value,
38
      name: this.form.get('name').value,
39
      password: this.form.get('password').value
40
    });
41
 
          
42
    request.subscribe(() => {
43
      this.router.navigate(['/login']);
44
    })
45
  }
46
}



Note that the user is not logged in after registration. For this reason, the user is redirected to the login route when the registration was successful. The template for this component goes into src/app/register/register.component.html.

HTML




xxxxxxxxxx
1
26


 
1
<div class="grid-container">
2
  <div class="grid-x">
3
    <div class="small-12 medium-10 medium-offset-1 large-8 large-offset-2 cell">
4
      <form [formGroup]="form" (ngSubmit)="onSubmit()">
5
        <h2>Sign Up</h2>
6
        <p>Please enter your details</p>
7
        <label class="full-width-input">
8
          Email
9
          <input type="text" placeholder="Email" formControlName="email" required>
10
        </label>
11
        <label class="full-width-input">
12
          Name
13
          <input type="text" placeholder="Name" formControlName="name" required>
14
        </label>
15
        <label class="full-width-input">
16
          Password
17
          <input type="password" placeholder="Password" formControlName="password" required>
18
        </label>
19
        <button class="button">Register</button>
20
      </form>
21
      <div class="login-link">
22
        Already registered? <a routerLink="/login">Login Here!</a>
23
      </div>
24
    </div>
25
  </div>
26
</div>



Creating the component for logging in follows the same steps.

Shell




xxxxxxxxxx
1


 
1
ng generate component login



In src/app/login/login.component.ts, create the logic for showing the form and using AuthService to log in.

TypeScript




xxxxxxxxxx
1
38


 
1
import { Component, OnInit } from '@angular/core';
2
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
3
import { AuthService } from '../auth.service';
4
 
          
5
@Component({
6
  selector: 'app-login',
7
  templateUrl: './login.component.html',
8
  styleUrls: ['./login.component.css']
9
})
10
export class LoginComponent implements OnInit {
11
  form: FormGroup;
12
  public loginInvalid: boolean;
13
  private formSubmitAttempt: boolean;
14
 
          
15
  constructor(private fb: FormBuilder, private authService: AuthService) {
16
  }
17
 
          
18
  ngOnInit() {
19
    this.form = this.fb.group({
20
      email: ['', Validators.email],
21
      password: ['', Validators.required]
22
    });
23
  }
24
 
          
25
  async onSubmit() {
26
    this.loginInvalid = false;
27
    this.formSubmitAttempt = false;
28
    if (this.form.valid) {
29
      try {
30
        await this.authService.login(this.form.value);      
31
      } catch (err) {
32
        this.loginInvalid = true;
33
      }
34
    } else {
35
      this.formSubmitAttempt = true;
36
    }
37
  }
38
}



The template src/app/login/login.component.html contains the HTML form for user email and password.

HTML




xxxxxxxxxx
1
22


 
1
<div class="grid-container">
2
  <div class="grid-x">
3
    <div class="small-12 medium-10 medium-offset-1 large-8 large-offset-2 cell">
4
      <form [formGroup]="form" (ngSubmit)="onSubmit()">
5
        <h2>Log In</h2>
6
        <p>Please login to continue</p>
7
        <label class="full-width-input">
8
          Email
9
          <input type="text" placeholder="Email" formControlName="email" required>
10
        </label>
11
        <label class="full-width-input">
12
          Password
13
          <input type="password" placeholder="Password" formControlName="password" required>
14
        </label>
15
        <button class="button">Login</button>
16
      </form>
17
      <div class="register-link">
18
        Not yet registered? <a routerLink="/register">Register Now</a>
19
      </div>
20
    </div>
21
  </div>
22
</div>



Finally, you need a route for showing the user’s profile.

Shell




xxxxxxxxxx
1


 
1
ng generate component profile



Copy the code below into src/app/profile/profile.component.ts. This component simply gets the profile data from the server and stores it for display.

TypeScript




xxxxxxxxxx
1
23


 
1
import { Component, OnInit } from '@angular/core';
2
import { ServerService } from '../server.service';
3
 
          
4
@Component({
5
  selector: 'app-profile',
6
  templateUrl: './profile.component.html',
7
  styleUrls: ['./profile.component.css']
8
})
9
export class ProfileComponent implements OnInit {
10
  name: string;
11
  email: string;
12
  
13
  constructor(private server: ServerService) { }
14
 
          
15
  ngOnInit() {
16
    this.server.request('GET', '/profile').subscribe((user: any) => {
17
      if (user) {
18
        this.name = user.name;
19
        this.email = user.email;
20
      }
21
    });
22
  }
23
}



The template in src/app/profile/profile.component.html simply displays the result.

HTML




xxxxxxxxxx
1
15


 
1
<div class="grid-container">
2
  <div class="grid-x">
3
    <div class="small-12 medium-10 medium-offset-1 large-8 large-offset-2 cell">
4
      <h2>Profile</h2>
5
      <h3>Name</h3>
6
      <p>
7
        {{name}}
8
      </p>
9
      <h3>Email</h3>
10
      <p>
11
        {{email}}
12
      </p>
13
    </div>
14
  </div>
15
</div>



OK, now I’ve thrown a lot of code at you. But it’s all quite simple really. The first two components display a form to the user, and, when submitted, the data is sent to the server. The last component acquires data from the server and display it. To make the whole thing work, some modules need to be imported. Open src/app/app.module.ts and add the following imports.

TypeScript




xxxxxxxxxx
1


 
1
import { HttpClientModule } from '@angular/common/http';
2
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
3
import { AuthService } from './auth.service';



Then, add the following to the imports array.

TypeScript




xxxxxxxxxx
1
10


 
1
@NgModule({
2
  ...
3
  imports: [
4
    ..
5
    HttpClientModule,
6
    FormsModule,
7
    ReactiveFormsModule  
8
  ],
9
  ...
10
})



Finally, add AuthService to the providers array.

TypeScript




xxxxxxxxxx
1


 
1
@NgModule({
2
  ...
3
  providers: [AuthService],
4
  bootstrap: [AppComponent]
5
})



The last thing left to do is to register the component with the router. Open src/app/app-routing.module.ts and replace its content with the following code.

TypeScript




xxxxxxxxxx
1
18


 
1
import { NgModule } from '@angular/core';
2
import { Routes, RouterModule } from '@angular/router';
3
import { LoginComponent } from './login/login.component';
4
import { RegisterComponent } from './register/register.component';
5
import { ProfileComponent } from './profile/profile.component';
6
 
          
7
const routes: Routes = [
8
  { path: '', component: RegisterComponent },
9
  { path: 'login', component: LoginComponent },
10
  { path: 'register', component: RegisterComponent },
11
  { path: 'profile', component: ProfileComponent },
12
];
13
 
          
14
@NgModule({
15
  imports: [RouterModule.forRoot(routes)],
16
  exports: [RouterModule]
17
})
18
export class AppRoutingModule { }



Your client is ready to try out. Start it by running the following command.

Shell




xxxxxxxxxx
1


 
1
ng serve -o



The client allows a user to register, then log in, and view their profile data. Is this all there is to know about JSON Web Tokens? No, I have not covered a number of issues. In terms of user experience, it would be nice if the /profile route could be protected in the client. Currently, a user that is not logged in to the server can still navigate to the /profile route. The server will refuse to send any data, so an empty page will be presented.

Another big topic that I have completely avoided covers token expiration and refreshing tokens when a user interacts with a website. Both are necessary to guarantee security while also providing a good user experience.

Build Secure JWT Authentication in Angular and Express

Okta provides authentication services that can be easily integrated into your application. The Okta service is based on JWT, and it takes care of all the issues related to security and user experience. You don’t need to store passwords, generate tokens yourself, or think about automatically refreshing them. To start off, you will need a developer account with Okta.

In your browser, navigate to developer.okta.com, click on Create Free Account, and enter your details. You will receive an activation email to finish creating your account. Once you are done, you will be taken to your developer dashboard. Click on the Add Application button to create a new application. Start by creating a new single-page application. Choose Single Page App and click Next.

Creating a new aplication

On the next page, you will need to edit the default settings. Make sure that the port number is 4200. This is the default port for Angular applications. Then click Done.

Adding application credentials

That’s it. You should now see a Client ID which you will need to paste into your JavaScript code.

Express Server for Authentication

The server that uses authentication using the Okta service does not need to implement any user registration or login. Registration is, of course, useful to keep track of user data, but it is not strictly necessary. Create a new directory called okta-server and run npm init -y in it as with the jwt-server. The libraries needed are slightly different.

Shell




xxxxxxxxxx
1


 
1
npm install -E cors@2.8.5 nodemon@1.18.10 express@4.16.4 \
2
  @okta/jwt-verifier@0.0.14 body-parser@1.18.3 express-bearer-token@2.2.0



The main application file index.js is the same as jwt-server/index.js. The authentication middleware auth.js looks slightly different because it now uses Okta.

JavaScript




xxxxxxxxxx
1
22


 
1
const OktaJwtVerifier = require('@okta/jwt-verifier');
2
 
          
3
const oktaJwtVerifier = new OktaJwtVerifier({
4
  issuer: 'https://{yourOktaDomain}/oauth2/default',
5
  clientId: '{yourClientId}'
6
});
7
 
          
8
function oktaAuth(req, res, next) {
9
  if (!req.token) {
10
    return res.status(403).send({ auth: false, message: 'No token provided' });
11
  }
12
 
          
13
  oktaJwtVerifier.verifyAccessToken(req.token).then(function(jwt) {
14
    req.userId = jwt.claims.uid;
15
    req.userEmail = jwt.claims.sub;
16
    next();
17
  }, function(err) {
18
    return res.status(500).send({ auth: false, message: 'Could not authenticate token' });
19
  });
20
}
21
 
          
22
module.exports = oktaAuth;



Here, {yourClientId} is the client ID from the application that you created earlier in the Okta dashboard. The router implementation in profile.js only contains a single route. I have removed the /register and /login routes and only kept the /profile route.

JavaScript




xxxxxxxxxx
1
11


 
1
var express = require('express');
2
var oktaAuth = require('./auth');
3
 
          
4
var router = express.Router();
5
 
          
6
router.get('/profile', oktaAuth, function(req, res, next) {
7
  console.log('ME', req.userId);
8
  res.status(200).send({id: req.userId, email: req.userEmail});
9
});
10
 
          
11
module.exports = router;



This route returns the data contained in the token. You could choose to use a database to store additional data and send it to the client, but I want to show you here that this is not required.

Add the following line to the scripts section of package.json.

JSON




xxxxxxxxxx
1


 
1
"start": "nodemon server.js",



Start the server with npm start.

Single Sign-On for Your Angular Client

Start off in the same way as creating the jwt-client application, but call it okta-client.

Shell




xxxxxxxxxx
1


 
1
ng new okta-client --routing --style=css  



Install foundation-sites and ngx-foundation, and then edit src/style.css and src/app/app.component.html in the same way, as with the Angular client in the previous section.

Shell




xxxxxxxxxx
1


 
1
npm install -E foundation-sites@6.5.3 ngx-foundation@1.0.8



Edit src/styles.css and paste in the imports for the Foundation styles.

CSS




xxxxxxxxxx
1


 
1
 
          
2
@import '~foundation-sites/dist/css/foundation.min.css';
3
@import '~ngx-foundation/dist/css/ngx-foundation.min.css';



Copy src/app/app.component.html from jwt-client to okta-client.

In src/app/app.component.html, on the first line, change *ngIf="authService.isLoggedIn | async as isLoggedIn" to *ngIf="isLoggedIn
| async as isLoggedIn".

HTML




xxxxxxxxxx
1


 
1
<div class="top-bar" *ngIf="isLoggedIn | async as isLoggedIn">



Next, install the Okta packages.

Shell




xxxxxxxxxx
1


 
1
npm install -E @okta/okta-angular@1.2.1 @okta/okta-signin-widget@2.19.0



Just as before, create a server service.

Shell




xxxxxxxxxx
1


 
1
ng generate service server



The implementation of the service in src/app/server.service.ts is very similar to the previous client. The only difference is that the JWT token is obtained through the OktaAuthService.

TypeScript




xxxxxxxxxx
1
63


 
1
import { Injectable } from '@angular/core';
2
import { HttpClient, HttpParams } from '@angular/common/http';
3
import { OktaAuthService } from '@okta/okta-angular';
4
import { Subject } from 'rxjs';
5
 
          
6
const baseUrl = 'http://localhost:10101';
7
 
          
8
@Injectable({
9
  providedIn: 'root'
10
})
11
export class ServerService {
12
 
          
13
  constructor(public oktaAuth: OktaAuthService, private http: HttpClient) {
14
  }
15
 
          
16
  request(method: string, route: string, data?: any) {
17
    if (method === 'GET') {
18
      return this.get(route, data);
19
    }
20
 
          
21
    const subject = new Subject<any>();
22
 
          
23
    this.oktaAuth.getAccessToken().then((token) => {
24
      const header = (token) ? {Authorization: `Bearer ${token}`} : undefined;
25
 
          
26
      const request = this.http.request(method, baseUrl + route, {
27
        body: data,
28
        responseType: 'json',
29
        observe: 'body',
30
        headers: header
31
      });
32
 
          
33
      request.subscribe(subject);
34
    });
35
 
          
36
    return subject;
37
  }
38
 
          
39
  get(route: string, data?: any) {
40
    const subject = new Subject<any>();
41
 
          
42
    this.oktaAuth.getAccessToken().then((token) => {
43
      const header = (token) ? {Authorization: `Bearer ${token}`} : undefined;
44
 
          
45
      let params = new HttpParams();
46
      if (data !== undefined) {
47
        Object.getOwnPropertyNames(data).forEach(key => {
48
          params = params.set(key, data[key]);
49
        });
50
      }
51
 
          
52
      const request = this.http.get(baseUrl + route, {
53
        responseType: 'json',
54
        headers: header,
55
        params
56
      });
57
 
          
58
      request.subscribe(subject);
59
    });
60
 
          
61
    return subject;
62
  }
63
}



The client still contains a login component, but in this case, it simply contains a widget provided by the @okta/okta-signin-widget library.

Shell




x


 
1
 ng generate component login --inlineStyle=true --inlineTemplate=true 



Modify the contents of src/app/login/login.component.ts so it looks like the following code: 

TypeScript




xxxxxxxxxx
1
55


 
1
import { Component, OnInit } from '@angular/core';
2
import { Router, NavigationStart} from '@angular/router';
3
import { OktaAuthService } from '@okta/okta-angular';
4
import * as OktaSignIn from '@okta/okta-signin-widget';
5
 
          
6
@Component({
7
  selector: 'app-login',
8
  template: `
9
    <div class="grid-container">
10
      <div class="grid-x">
11
        <div class="small-12 medium-10 medium-offset-1 large-8 large-offset-2 cell">
12
          <div id="okta-signin-container"></div>
13
        </div>
14
      </div>
15
    </div>
16
  `,
17
  styles: []
18
})
19
export class LoginComponent implements OnInit {
20
  widget = new OktaSignIn({
21
    baseUrl: 'https://{yourOktaDomain}'
22
  });
23
 
          
24
  constructor(private oktaAuth: OktaAuthService, router: Router) {
25
    // Show the widget when prompted, otherwise remove it from the DOM.
26
    router.events.forEach(event => {
27
      if (event instanceof NavigationStart) {
28
        switch (event.url) {
29
          case '/login':
30
          case '/profile':
31
            break;
32
          default:
33
            this.widget.remove();
34
            break;
35
        }
36
      }
37
    });
38
  }
39
 
          
40
  ngOnInit() {
41
    this.widget.renderEl({
42
      el: '#okta-signin-container'},
43
      (res) => {
44
        if (res.status === 'SUCCESS') {
45
          this.oktaAuth.loginRedirect('/profile', { sessionToken: res.session.token });
46
          // Hide the widget
47
          this.widget.hide();
48
        }
49
      },
50
      (err) => {
51
        throw err;
52
      }
53
    );
54
  }
55
}



Copy the jwt-client/src/app/profile directory into your okta-client project and change ProfileComponent to retrieve the name from Okta’s Angular SDK.

TypeScript




xxxxxxxxxx
1
29


 
1
import { Component, OnInit } from '@angular/core';
2
import { ServerService } from '../server.service';
3
import { OktaAuthService } from '@okta/okta-angular';
4
 
          
5
@Component({
6
  selector: 'app-profile',
7
  templateUrl: './profile.component.html',
8
  styleUrls: ['./profile.component.css']
9
})
10
export class ProfileComponent implements OnInit {
11
  id: string;
12
  email: string;
13
  name: string;
14
 
          
15
  constructor(private server: ServerService, oktaAuth: OktaAuthService) { 
16
    oktaAuth.getUser().then(user => {
17
      this.name = user.name;
18
    })
19
  }
20
 
          
21
  ngOnInit() {
22
    this.server.request('GET', '/profile').subscribe((user: any) => {
23
      if (user) {
24
        this.id = user.id;
25
        this.email = user.email;
26
      }
27
    });
28
  }
29
}



Next, open src/app/app.module.ts and paste the following code into it.

TypeScript




xxxxxxxxxx
1
36


 
1
import { BrowserModule } from '@angular/platform-browser';
2
import { NgModule } from '@angular/core';
3
import { HttpClientModule } from '@angular/common/http';
4
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
5
import { OKTA_CONFIG, OktaAuthModule } from '@okta/okta-angular';
6
 
          
7
import { AppRoutingModule } from './app-routing.module';
8
import { AppComponent } from './app.component';
9
import { LoginComponent } from './login/login.component';
10
import { ProfileComponent } from './profile/profile.component';
11
 
          
12
const oktaConfig = {
13
  issuer: 'https://{yourOktaDomain}/oauth2/default',
14
  redirectUri: 'http://localhost:4200/implicit/callback',
15
  clientId: '{yourClientId}',
16
  scope: 'openid profile'
17
};
18
 
          
19
@NgModule({
20
  declarations: [
21
    AppComponent,
22
    LoginComponent,
23
    ProfileComponent
24
  ],
25
  imports: [
26
    BrowserModule,
27
    AppRoutingModule,
28
    HttpClientModule,
29
    FormsModule,
30
    ReactiveFormsModule,
31
    OktaAuthModule
32
  ],
33
  providers: [{ provide: OKTA_CONFIG, useValue: oktaConfig }],
34
  bootstrap: [AppComponent]
35
})
36
export class AppModule { }



All that is left to do now is to register the components with the router in src/app/app-routing.module.ts.

TypeScript




xxxxxxxxxx
1
23


 
1
import { NgModule } from '@angular/core';
2
import { Routes, RouterModule } from '@angular/router';
3
import { OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular';
4
 
          
5
import { LoginComponent } from './login/login.component';
6
import { ProfileComponent } from './profile/profile.component';
7
 
          
8
export function onAuthRequired({ oktaAuth, router }) {
9
  router.navigate(['/login']);
10
}
11
 
          
12
const routes: Routes = [
13
  { path: '', component: ProfileComponent, canActivate: [OktaAuthGuard], data: { onAuthRequired }  },
14
  { path: 'login', component: LoginComponent },
15
  { path: 'profile', component: ProfileComponent, canActivate: [OktaAuthGuard], data: { onAuthRequired }  },
16
  { path: 'implicit/callback', component: OktaCallbackComponent }
17
];
18
 
          
19
@NgModule({
20
  imports: [RouterModule.forRoot(routes)],
21
  exports: [RouterModule]
22
})
23
export class AppRoutingModule { }



Finally, open src/app/app.component.ts and replace its contents with the following code.

TypeScript




xxxxxxxxxx
1
25


 
1
import { Component, OnInit } from '@angular/core';
2
import { OktaAuthService } from '@okta/okta-angular';
3
import { BehaviorSubject } from 'rxjs';
4
 
          
5
@Component({
6
  selector: 'app-root',
7
  templateUrl: './app.component.html',
8
  styleUrls: ['./app.component.css']
9
})
10
export class AppComponent implements OnInit {
11
  title = 'okta-client';
12
  isLoggedIn = new BehaviorSubject<boolean>(false);
13
 
          
14
  constructor(public oktaAuth: OktaAuthService) {
15
    this.oktaAuth.$authenticationState.subscribe(this.isLoggedIn);
16
  }
17
 
          
18
  ngOnInit() {
19
    this.oktaAuth.isAuthenticated().then((auth) => {this.isLoggedIn.next(auth)});
20
  }
21
 
          
22
  onLogout() {
23
    this.oktaAuth.logout('/');
24
  }
25
}



Your Angular app now implements authentication using Okta and JWTs! It guards the routes that should be accessed and automatically redirects the user to the login page when they are not logged in. In contrast to the example in the previous section, the implementation in this section is complete. The Okta libraries take care of all remaining issues that were not covered by the bare-bones JWT implementation.

You can test the client by running the ng serve command as usual. Enter valid credentials when prompted.

User sign in in Angular client

Once logged in, you will be redirected to the profile page and you’ll see your user information, just like before.

User successfully logged in

Learn More About Angular and JWTs

I hope that, in this tutorial, I have given you some insight into JSON Web Tokens and their uses. They solve some of the problems faced by traditional session based authentication by encrypting the user information and passing it back to the client. I have shown you how to implement a server and client using JWT. This example showed you the basics but, in order to be used for a production server, additional steps would need to be taken. Okta simplifies the task of creating token-based authentication. Using only a few steps you can implement a fully working server and client.

The code for this tutorial can be found on GitHub at oktadeveloper/angular-jwt-authentication-example.

If you want to learn more about JWT, Okta, or implementing RESTful servers with Angular and Node, check out the following links.

Topics:
angular, authentication, javascript, jwt, nodejs, typescript

Published at DZone with permission of Holger Schmitz , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}