Validating JWT in Angular and Node JS: A Step-by-Step Guide (Part 2)

Posted by

How to validate JWT in Angular and Node JS (Part 2)

How to validate JWT in Angular and Node JS (Part 2)

In the first part of this series, we discussed how to generate and send JWT tokens from a Node JS server to an Angular client. In this article, we will focus on how to validate JWT tokens in Angular and Node JS.

Validating JWT in Angular

In Angular, we can use the Angular JwtModule to validate JWT tokens. First, we need to install the module using npm:


npm install @auth0/angular-jwt

After installing the module, we need to configure it in our Angular application. We can do this by adding the following code to our app.module.ts file:

        import { JwtModule } from '@auth0/angular-jwt';

        export function tokenGetter() {
            return localStorage.getItem('access_token');
        }

        @NgModule({
        imports: [
            JwtModule.forRoot({
                config: {
                    tokenGetter: tokenGetter,
                    allowedDomains: ['example.com'],
                    disallowedRoutes: ['example.com/login']
                }
            })
        ]
        })
    

With this configuration, the JwtModule will automatically validate the JWT token for every HTTP request made by our Angular application.

Validating JWT in Node JS

In Node JS, we can use the jsonwebtoken library to validate JWT tokens. First, we need to install the library using npm:


npm install jsonwebtoken

After installing the library, we can use the verify method to validate the JWT token in our Node JS application:

        const jwt = require('jsonwebtoken');

        // Extract the token from the request header
        const token = req.headers.authorization.split(' ')[1];

        jwt.verify(token, 'secretKey', (err, decoded) => {
            if (err) {
                res.status(401).json({ message: 'Invalid token' });
            } else {
                // Token is valid, continue with the request
            }
        });
    

With these steps, we can successfully validate JWT tokens in both our Angular and Node JS applications. This adds an extra layer of security to our application and helps prevent unauthorized access.

Stay tuned for the next part of this series, where we will discuss how to refresh JWT tokens in Angular and Node JS.