2022-08-12
1738
#nestjs
Clara Ekekenta
127096
Aug 12, 2022 â‹… 6 min read

How to implement JWT authentication in NestJS

Clara Ekekenta Software Engineer and perpetual learner with a passion for OS and expertise in Python, JavaScript, Go, Rust, and Web 3.0.

Recent posts:

Vue logo over a brown background.

A guide to two-way binding in Vue

Learn how to implement one-way and two-way data binding in Vue.js, using v-model and advanced techniques like defineModel for better apps.

David Omotayo
Nov 22, 2024 â‹… 10 min read
TypeScript logo over a pink and white background.

Drizzle vs. Prisma: Which ORM is best for your project?

Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.

Temitope Oyedele
Nov 21, 2024 â‹… 10 min read
Practical Implementation Of The Rule Of Least Power For Developers

Practical implementation of the Rule of Least Power for developers

It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.

Timonwa Akintokun
Nov 21, 2024 â‹… 8 min read
Rust logo over black marble background.

Handling memory leaks in Rust

Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.

Ukeje Goodness
Nov 20, 2024 â‹… 4 min read
View all posts

9 Replies to "How to implement JWT authentication in NestJS"

  1. Also I think you messed up the order of steps for the auth module since the local strategy needs the auth service which is mentioned further down on how to create it.

  2. missing :

    npm install –save @nestjs/passport passport passport-local
    npm install –save-dev @types/passport-local

    and local strategy

    import { Strategy } from ‘passport-local’;
    import { PassportStrategy } from ‘@nestjs/passport’;
    import { Injectable, UnauthorizedException } from ‘@nestjs/common’;
    import { AuthService } from ‘./auth.service’;

    @Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private authService: AuthService) {
    super();
    }

    async validate(username: string, password: string): Promise {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
    throw new UnauthorizedException();
    }
    return user;
    }
    }

  3. So, I’m rendering templates via Nest.js, and some of those templates include client-side JavaScript (via tags) that needs to do API requests from the browser. What is the proper way to send the access token to the frontend so that it can be used via the JavaScript running in the browser? Should I just set the access token in the pre-rendered HTML (e.g. as an attribute of the element, so that the client-side JavaScript can just query the DOM to get the token for API requests? Or is that unsafe/non-secure?

    1. Sending access tokens to the frontend, especially if they’re intended to be used by client-side JavaScript, is a sensitive area that requires a security-focused approach. Here are some common practices and considerations:

      HTTP-Only Cookies: One common method for sending tokens to the frontend securely is to use HTTP-only cookies. These cookies cannot be accessed through JavaScript, thereby reducing the risk of cross-site scripting (XSS) attacks. But this method isn’t directly useful if your client-side script needs to access the token.

      Avoid Inline JavaScript: When you’re rendering templates server-side, avoid placing sensitive data in inline JavaScript or in the DOM. This can expose the data to XSS attacks.

      Frontend Session: If your frontend app requires the token, you might consider a strategy where you fetch the token in a secured way after the initial page load. This might be done through a secure API endpoint that returns the token as a JSON payload, which your frontend app can then store in memory (not in local storage due to security concerns). This token can then be used for subsequent API requests.

      Short-Lived Tokens: If tokens must be exposed to frontend code, make sure they are short-lived. This reduces the potential damage in case of exposure.

      Avoid Local Storage for Sensitive Tokens: The Web Storage (local storage and session storage) is vulnerable to XSS attacks. If an attacker can run JavaScript on your page, they can retrieve the tokens stored there. Instead, if you must store a token on the frontend, consider keeping it in a JavaScript variable which will exist only for the life of the page.

      Content Security Policy (CSP): Implement a strong CSP for your web application. This reduces the risk of XSS attacks by controlling which scripts and resources can be loaded and executed.

      Always Use HTTPS: Always ensure your application runs over HTTPS. This encrypts the traffic between the client and the server, protecting the token from being intercepted.

      Refresh Tokens: If using short-lived access tokens, also use refresh tokens (stored securely server-side) to obtain a new access token once the old one expires. This way, even if an access token is exposed, its short lifespan combined with the inability to refresh it limits potential damage.

      In summary, if your client-side JavaScript absolutely requires the access token, ensure you’re following best practices to minimize risks, such as those mentioned above. Ideally, reduce direct exposure of tokens to frontend code as much as possible.

  4. So what’s the reason behind using passport-local middleware, when one can just verify password in login method and call “validate” afterwards or throw an error? This middleware is useless in this case

  5. I am getting this error
    plz advise.Thanks

    ERROR [ExceptionHandler] JwtStrategy requires a secret or key
    TypeError: JwtStrategy requires a secret or key

Leave a Reply