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:

Eleventy Adoption Guide: Overview, Examples, And Alternatives

Eleventy adoption guide: Overview, examples, and alternatives

Eleventy (11ty) is a compelling solution for developers seeking a straightforward, performance-oriented approach to static site generation.

Nelson Michael
May 7, 2024 â‹… 8 min read
6 CSS Tools For More Efficient And Flexible CSS Handling

6 CSS tools for more efficient and flexible CSS handling

Explore some CSS tools that offer the perfect blend of efficiency and flexibility when handling CSS, such as styled-components and Emotion.

Fimber Elemuwa
May 7, 2024 â‹… 7 min read
Leveraging React Server Components In Redwoodjs

Leveraging React Server Components in RedwoodJS

RedwoodJS announced support for server-side rendering and RSCs in its Bighorn release. Explore this feature for when it’s production-ready.

Stephan Miller
May 6, 2024 â‹… 9 min read
Exploring The Aha Stack: Astro, Htmx, Alpine — A Complete Tutorial With A Demo Project And Comparison To Other Stacks

Exploring the AHA stack: Tutorial, demo, and comparison

The AHA stack — Astro, htmx, and Alpine — is a solid web development stack for smaller apps that emphasize frontend speed and SEO.

Oyinkansola Awosan
May 3, 2024 â‹… 13 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