Setting up authentication with JSON Web Tokens (JWT) in Angular can be a crucial aspect of your web development projects. In this article, we will guide you through the process of integrating JWT authentication into your Angular application.
JSON Web Tokens are a secure and efficient way to authenticate users and transmit information between parties. They consist of three parts: a header, a payload, and a signature. When a user logs in, they receive a token containing encoded information about their identity and permissions.
To begin setting up JWT authentication in Angular, you first need to install the necessary dependencies. You can do this by running the following command in your Angular project directory:
npm install @auth0/angular-jwt
This package provides utilities for working with JWTs in Angular applications. Once you have installed the package, you can import the JwtModule into your Angular app module:
import { JwtModule } from '@auth0/angular-jwt';
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem('access_token');
},
allowedDomains: ['example.com'],
disallowedRoutes: ['example.com/login']
}
})
In the configuration above, we are setting up the JwtModule to retrieve the JWT token from the local storage. You can customize this configuration based on your application's requirements, such as allowed domains and disallowed routes.
Next, you need to create a service to handle authentication operations in your Angular application. This service will be responsible for logging users in, storing their tokens, and handling token expiration:
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(public jwtHelper: JwtHelperService) {}
public isAuthenticated(): boolean {
const token = localStorage.getItem('access_token');
return !this.jwtHelper.isTokenExpired(token);
}
public login(token: string): void {
localStorage.setItem('access_token', token);
}
public logout(): void {
localStorage.removeItem('access_token');
}
}
In this AuthService class, we are using the JwtHelperService from the @auth0/angular-jwt package to check the token's expiration status. The login and logout methods allow you to manage the user's authentication status within the application.
Finally, you can leverage the AuthService in your Angular components to handle authentication logic. For example, you can protect routes by implementing a router guard that checks the user's authentication status before navigating to a route:
// app.routing.ts
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent
}
];
In the AuthGuard class, you can use the AuthService to determine whether the user is authenticated and redirect them accordingly. By integrating JWT authentication into your Angular application, you can enhance security and user experience in a seamless manner.