Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
vinod edited this page Dec 29, 2023 · 1 revision

Welcome to the nestjs-jwt-auth-cookie-mongoose wiki!

NestJS JWT Service with Cookie and Authorization

This repository contains a NestJS application showcasing JWT (JSON Web Token) authentication using cookies and authorization implementation.

Features

  • JWT Authentication: Implementation of JWT-based authentication using NestJS.
  • Cookie-based Tokens: Store JWT tokens in HTTP-only cookies for secure communication.
  • Authorization Middleware: Middleware for protecting routes and verifying user authorization.

Cookie-Based Authentication Implementation with Nest.js

Prerequisites

  • Node.js
  • Basic knowledge of Nest.js
  • Basic knowledge of Command Line

Getting Started

This guide focuses on cookie-based authentication in Nest.js. To begin, bootstrap the project by installing Nest CLI globally in your environment. Refer to the official docs for detailed instructions.

Implementing Basic JWT Authentication with @nestjs/jwt

Follow the Nest.js documentation to add basic authentication using @nestjs/jwt. Initially, the application uses a bearer token for authorization headers, which we'll later transition into an http-only cookie. @Module({ imports: [ UserModule, JwtModule.register({ global: true, secret: jwtConstants.secret, signOptions: { expiresIn: '60s' } }), ], providers: [ AuthService, { provide: APP_GUARD, useClass: AuthGuard, } ], controllers: [AuthController], exports: [AuthService], }) export class AuthModule {}

Update the expiration time in 'src/auth/auth.module.ts' to a longer duration for testing purposes.

Testing Authentication

Verify the authentication by obtaining a new access token and accessing the protected routes, like the users, using Postman's Authorization tab.

Migrating from Authorization Header to HTTP-Only Cookie

To enhance security and reduce client-side overhead, transition from sending tokens in the body to using http-only cookies.

Making Code Changes

  • Update 'src/auth/auth.controller.ts' to include logic for setting the access token as an http-only cookie in the response.

  • Ensure the cookie has properties like httpOnly: true, secure: false, sameSite: 'lax', and an expiration date. ` async signIn(@Body() signInDto: SignInDto, @Res() res: Response) { const token = await this.authService.signIn( signInDto.email, signInDto.password );

    res.cookie("access_token", token.access_token, { httpOnly: false, expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000), path: "/", sameSite: "none", secure: false, }); res.cookie("refresh_token", token.refresh_token, { httpOnly: false, expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000), path: "/", sameSite: "none", secure: false, });

    return sendResponse( res, HttpStatus.OK, statusMessage[HttpStatus.OK], true, null ); }`

Implementing Cookie Extraction

Download a npm package to parse cookies for easy access to request cookies in a structured format. private extractTokenFromCookie(request: Request): string | undefined { let isCookieAuth =${process.env.IS_COOKIE_AUTH}; let token = undefined; if (isCookieAuth === "true") { token = request?.cookies?.refresh_token ?? null; } else { const [type, tokenValue] = request.headers.authorization?.split(" ") ?? []; token = type === "Bearer" ? tokenValue : undefined; } return token ? token : undefined; }

Conclusion

Cookie-based authentication provides improved security over storing tokens in client-accessible locations like local storage. Although this implementation might have risks like CSRF attacks, it's a preferred method in certain contexts.

Ensure to manage secrets securely in a real-world scenario, avoiding hardcoding sensitive information.

This article provides a step-by-step guide to implementing cookie-based authentication in Nest.js. Feedback and suggestions are welcomed.

Find the completed version of the project here.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.