Angular 8/9 JWT Authentication with Example in MEAN Stack

Posted at: April 14, 2020 4:18 PM

JWT token-based authentication in Angular 8/9 with example using web API. Web API has created in Node.js. We have used Guard, Interceptors, etc.

Before starting this lesson needs to learn previous lesson JWT Token Based Authentication using Passport in Node.js for creating web api.

Auth Service

Install jwt-decode for decode jwt token.

Import jwt-decode (import * as jwt_decode from 'jwt-decode';) in auth-service.ts for decode jwt token after user logged in and get token data like as iat, exp, sub, etc.

Login Method

Create login() method for access login api and return as Observable true or false. In this login method I have used tap RxJS pipeable operator thats return an Observable that is identical to the source. After login get user data using tap. mapTo() is also pipeable operator that's emits the given constant value on the output Observable every time the source Observable emits a value, means after successfully login return true otherwise return false.

Storing user data in localStorage

I have created doLogin() method for storing user data to localStorage as a string with key name currentUser. We can use user data anywhere in our application.

Get current user data from localStorage

Get current user data from localStorage and return as an object.

Decode JWT Token

Decode jwt token and get token data like as iat, exp, sub, etc.

isLoggedIn()

Create isLoggedIn() for check any where user logged in or not. In this method we have matched the current time and token expire time. If token expiry time is greater than the current time then returned true i.e. token.exp > currentTime otherwise return false and removed currentUser from localStorage by calling this.logout();.

Logout

After clicking logout button currentUser removed from localStorage.

Complete code of auth-service.ts

Auth Guard

Create auth-guard.ts in auth module.

You can use guard for access route only authorized user. Guard protects route to unauthorized users. There are five types of guards.

  • canActivate: If return true, navigation will continue. If returns false, navigation will be cancelled.
  • canActivateChild: you can also protect child routes with the CanActivateChild guard. It is similar to the CanActivate guard
  • canDeactivate: to mediate navigation away from the current route. You can handle unsaved changes.
  • resolve: fetch data before navigating. It's preferable to pre-fetch data from the server so it's ready the moment the route is activated.
  • canLoad: It is used for loading of features or lazy loading module. If used canLoad guard in route then only load module once the user is logged in.

Create method checkLogin() with pass parameter url and return as boolean in AuthGuard. In this method we have checked If user logged in then return true. If the user is not logged in, you store the attempted URL the user came from using the RouterStateSnapshot.url and tell the router to navigate to a login page. This secondary navigation automatically cancels the current navigation checkLogin() returns false. This method is called in canActivate and canLoad guards.

Complete code of AuthGuard

canLoad Guard

import { AuthGuard } from '../auth/auth.guard'; into backend-layout-route.ts. Add a CanLoad guard that only loads the DashboardModule and ProductModule once the user is logged in and attempts to access the dashboard and product feature area.

Dashboard: canActivate Guard

import { AuthGuard } from '../auth/auth.guard'; into dashboard-routing.module.ts. Add a canActivate Guard to the access DashboardComponent once the user is logged in.

Error Message

Note: If you have created message component in app folder, then remove it and also remove from app.module.ts. And create message component in shared module and also exports this for accessing this component in another module for showing http error message.

Message Component

message.component.ts

message.component.html

shared.module.ts

Exports to the MessageComponent for access this component into another module.

Login Component

Create a login reactive form with username and password field. After submitting the login form if user logs in successfully, then redirect to the dashboard page.

login.component.ts

Show error messages by calling message component into login.component.html.

login.component.html

Logout

Create logout link in BackendHeaderComponent

backend-header.component.ts

Show error message by calling message component into backend-header.component.html for all modules.

backend-header.component.html

Dashboard Component

dashboard.component.html

Http Interceptors

HTTP Interceptor is a major feature of @angular/common/http. Interceptors that inspect and transform HTTP requests from your application to the server. Using interceptors you can do some work with a single HTTP request or response. You can use multiple interceptors in your application. I have used token interceptor to send a token from the client to the server in every single request.

Token Interceptor

Create an interceptor src/app/http-interceptors/token.interceptor.ts. If user logged in then send token to the server each http request through Header.

src/app/http-interceptors/token.interceptor.ts

Create a file src/app/http-interceptors/index.ts that gathers all the interceptor providers into an httpInterceptorProviders array. HTTP_INTERCEPTORS a multi-provider token that represents the array of registered HttpInterceptor objects. Import TokenInterceptor into this file.

Then import and add it to the AppModule providers array like this.

app.module.ts

Conclusion

In this lesson we have learned login with jwt token in Angular 8/9 using web api. We have used Guards like as canActivate, canActivateChild and canLoad. After a user logged in send token from client to the server using HTTP Interceptors in each single request. Only authorized user can access a restricted area.

This lesson also available on YouTube
angular 8 authentication example angular 8/9 jwt authentication example angular 8/9 jwt authentication angular 8/9 login with web api angular 8/9 login page angular 8/9 login example mean stack login and registration angular 8/9 mean stack authentication angular 8/9 mean stack login and registration angular 8/9

Please leave comments

1 Comments