Authentication in Nest.js: JWT Protected APIs and Refresh Token

Поділитися
Вставка
  • Опубліковано 5 сер 2024
  • ❤️Please Support me by subscribing to my channel 👉🏻www.youtube.com/@sakuradev?su...
    In this Nest.js authentication tutorial, you'll learn how to create a secure and effective authentication system using three different strategies: local, JWT access tokens, and refresh tokens. We'll start by exploring the basics of each strategy and understanding how they work together to create a solid authentication solution. Then, we'll dive into implementing the local strategy, which involves authenticating users with a username and password. Next up is configuring our API routes to require a valid JWT access token, ensuring that only authenticated users can access protected resources. Finally, we'll cover how to implement refresh tokens, which allow users to obtain new access tokens without having to re-enter their credentials. Throughout the tutorial, we'll provide real world example to help you build a secure and reliable authentication system in Nest.js. Whether you're new to Nest.js or an experienced developer looking to enhance your skills, this tutorial has everything you need to get started with Nest.js authentication!
    #JWT #refreshtokens #websecurity #APIsecurity #backenddevelopment #NodeJS #localstrategy
    #webdevelopment
    🚀 Crash Course of Nest.JS : • Nest.js Crash Course :...
    ❤️ Subscribe to my channel / @sakuradev
    💻 Github Repo: github.com/vahid-nejad/nest-c...
    📖 Chapters:
    0:00 Intro
    0:29: Validating User Credentials
    5:35 Login function and creating jwt access tokens
    11:44 Passport local strategy: authenticate users with username and password
    14:42 Creating Local Strategy Guard
    15:42 Creating Login API Endpoint
    21:49 Testing Login API and Local Strategy
    25:24 JWT Strategy: Protect APIs with JWT
    35:52 Refresh Token
    46:00 Outro

КОМЕНТАРІ • 69

  • @lukekennedy8386
    @lukekennedy8386 Рік тому

    Thank you for this! I m looking forward to the TypeORM tutorials for NestJS. :D

  • @phillgames8057
    @phillgames8057 Рік тому +1

    thnks dude! such a great video! i've learning so much w/ this!. Greetings from Brazil!

    • @SakuraDev
      @SakuraDev  Рік тому

      Thanks for watching. I am glad it was helpful and also I am so proud to have many subscribers from Brazil. 🌹

  • @AlexCoronell
    @AlexCoronell Рік тому

    Thank you very much!!!

  • @gregoryalvim4615
    @gregoryalvim4615 Рік тому +1

    Thank you for this video! It was of great help for me.

  • @imthedaniels
    @imthedaniels Рік тому +4

    Greetings from Brazil, amazing tutorial, helped me a lot!

    • @SakuraDev
      @SakuraDev  Рік тому +1

      Thanks. I am really happy to have you from Brazil. 🌹

  • @yasserhy
    @yasserhy Рік тому +1

    I am stuck here. My refresh token is always coming without the payload encoded. I noticed that the the user passed to the refreshToken function seems to be empty. But when I use console.log(user), I can see the data. But when I try to use the data to populate the payload, the payload is always empty as if it cannot read any of the user properties. What is going on? Please note that I also checked the newly generated AccessToken that you produced, and it seems it is having the same issue

  • @ilyaincrypt0
    @ilyaincrypt0 Місяць тому

    i'm grateful for your videos ! Its simple and fast explanation what I ever see about oauth2

  • @overrevvv
    @overrevvv 6 місяців тому

    Thank you so much for this amazing video.

    • @SakuraDev
      @SakuraDev  6 місяців тому

      I'm really glad you like it 🙏

  • @PattyBeautCode
    @PattyBeautCode 11 місяців тому +3

    I really like how you teach these series ! Please build more authenticate and authorization NestJS app with key cloak 💥💥

    • @SakuraDev
      @SakuraDev  11 місяців тому +1

      I'm thrilled that you're enjoying the series! Your feedback means a lot. Thanks for the suggestion, creating an authentication and authorization NestJS app with Keycloak sounds like an excellent topic. I'll definitely take it into consideration for future content. Stay tuned for more engaging tutorials and keep up the enthusiasm for learning! 💪🌟

  • @abelmurua6980
    @abelmurua6980 8 місяців тому

    Nice video! Doubt: how is frontend (e.g. port:3000) going to grab that token without using sessions? the response is still in backend, frontend has no clue what the token is so far... Any way to have the callback URL with its token?

  • @floviskabanda8044
    @floviskabanda8044 Місяць тому

    Hi
    How can I invalidate an access token after a user logs out ? Currently, even after the user logs out and I delete the refresh token from the database, they can still make requests with their access token as long as it is valid.

  • @maksymovych_maksym
    @maksymovych_maksym 6 місяців тому

    Thanks!
    The content is beneficial.

    • @SakuraDev
      @SakuraDev  6 місяців тому

      Glad it was helpful!

  • @leocrawf
    @leocrawf Рік тому +1

    Could you complete this by adding simple roles?

  • @AdiGunawan1
    @AdiGunawan1 Рік тому +4

    I saw refresh token and access token have same payload, I think refresh token can be access main jwt authguard too? referesh token was too waste. i've googling referesh token concept but nothing. you can create token and refresh token with same payload but the secret key must be different

    • @SakuraDev
      @SakuraDev  Рік тому +1

      Yes, you can use different key for refresh token. Thanks for bringing that to my attention🌷

  • @andreygazhala7577
    @andreygazhala7577 6 місяців тому

    Thanks

  • @JacobSucksAtCode
    @JacobSucksAtCode 6 місяців тому

    Great work bro!

    • @SakuraDev
      @SakuraDev  6 місяців тому

      Thank you! Cheers!

  • @nobodyeverybody8437
    @nobodyeverybody8437 7 місяців тому

    what if the tokens were saved as http only tokens?

  • @DevCodeBoost
    @DevCodeBoost 24 дні тому

    Thanks mate, you didn't mention how to generate the refresh token automatically with each request with nextjs for example!

  • @muchamadfaiz2391
    @muchamadfaiz2391 5 місяців тому

    amazing tutorial!! thank you for the video.. but i have a question how to implement dto on local strategy?

  • @rhythmk06
    @rhythmk06 Рік тому +2

    It would be great if you upload a video on integrating microservice with Nest.js using Kafka. Thanks!

    • @SakuraDev
      @SakuraDev  Рік тому +1

      Actually in our latest project in the company I work, we have used kafa for microservices in nest.js. mybe in the future I create a video about it.

  • @cuberos7430
    @cuberos7430 Рік тому +1

    Congratulations Excellent Tutorial Thanks Sakura

    • @SakuraDev
      @SakuraDev  Рік тому

      Thanks for your nice feedback🙏

  • @giakhanhho741
    @giakhanhho741 Рік тому +1

    where does passport compare that payload is correct?, i mean if you decode jwt from bearer header, you should see if payload is correct.

    • @SakuraDev
      @SakuraDev  Рік тому

      hi, passport.js does it under the hood.

    • @giakhanhho741
      @giakhanhho741 Рік тому

      @@SakuraDev i just dont know how can passport communicate with the db. I mean if you store id in the payload then after you decode token from header, you should check that id if it exist in db or not. Sorry if I am wrong

    • @yasserhy
      @yasserhy Рік тому

      @@giakhanhho741 the logic here has nothing to do with the database. this is your job to validate if that ID or Email is correct or not. the validation is against the whole generated JWT based on the payload you initially created it with. regardless if the email or username are correct or not. read more about JWT to understand the logic behind it

  • @user-nm8kl5on8y
    @user-nm8kl5on8y 4 місяці тому

    really asking, no offense. Is this really the correct way to implement the refresh token? By implementing this method of validating the refresh token (by simply validating the refresh token with the token secret), wouldn't add a new layer of security for the access token would it?
    I mean , as long as you have the refresh token, you'll be able to refresh the access token, this is the same as setting up a long-lived access token from the start, right? Except maybe using a different token refresh validation mechanism (not just using token secret).

    • @SakuraDev
      @SakuraDev  2 місяці тому

      Sorry for the late comment. I just saw this now. Usually in real world application, we keep the refresh tokens in a database like Redis. so for example we can easily revoke them and delete them from the db. this increase level of security of refresh tokens.

  • @jeetudewangan9836
    @jeetudewangan9836 Рік тому +1

    where and how we can store logged in user imformation like email, user_id, and role for further uses

    • @SakuraDev
      @SakuraDev  Рік тому

      with JWT based authentication, actually we dont keep the info of logged in users. If user has a valid jwt, then it is authenticated. but if we want to keep the info about the logged in users, we should go with the session based method.

  • @mertellialti
    @mertellialti Місяць тому

    is it okay to return role in refresh token with access token? how to handle role also?

    • @SakuraDev
      @SakuraDev  Місяць тому

      Access tokens are meant to be short-lived and ideally shouldn't contain sensitive information like roles. If the token is compromised, an attacker could potentially gain access to the user's role.
      Instead, use a Separate Role Endpoint: Upon successful refresh token validation, return a new access token but on a separate endpoint, fetch the user's information including the role. This separates concerns and keeps access tokens lean.

  • @guven8
    @guven8 6 місяців тому

    Im not sure this is correct, I can use the refresh token as an access token to authenticate the :id/comments route, so the access and refresh tokens are the same

    • @SakuraDev
      @SakuraDev  6 місяців тому +1

      Hi, thanks for bringing that to my attention. The solution to this problem is using different secret keys for access token and refresh token

  • @ej-developer8809
    @ej-developer8809 Рік тому +1

    good

  • @jaisuperawesome
    @jaisuperawesome 7 місяців тому

    I'm still waiting for comprehensive Typeorm course😆

  • @furkancakici8856
    @furkancakici8856 Рік тому +1

    Can you prepare a dockerize tutorial that simulates dev and prod environment? Thames 👌

    • @SakuraDev
      @SakuraDev  Рік тому

      Sure, I'd be happy to help with that. I will do it.

  • @hadirahmani7943
    @hadirahmani7943 Рік тому

    You created JwtStrategy class and defined that in auth provider and you don't used from that. why?

    • @SakuraDev
      @SakuraDev  Рік тому

      we don't use jwtStrategy directly. I used it to create a jwt-guard and then use that guard to protect my APIs.

    • @kevennyjs
      @kevennyjs 3 місяці тому

      @@SakuraDev how i do this? i need add a new "JwtModule.register"? in RefreshJwtStrategy i need change secretOrKey to refresh? can you detail this for me please?

  • @franciscooteiza
    @franciscooteiza 6 місяців тому

    It's falling APART and they won't stop it ALL from burning down over the 'message'

  • @iwmatt
    @iwmatt Рік тому +1

    Everyone writes guides about jwt token so cool, but no one wrote down what to do if an attacker stole a refreshToken

    • @SakuraDev
      @SakuraDev  Рік тому +1

      If an attacker steals a refreshToken, the best practice is to immediately revoke the refreshToken and any associated access tokens on the server-side. This way, the attacker will no longer be able to use those tokens to access protected resources. The user should also be notified about the potential security breach and advised to change their password and/or enable two-factor authentication to prevent further unauthorized access.

    • @iwmatt
      @iwmatt Рік тому

      @@SakuraDev I entered token_version in user.entity when a refresh_token is created, token_version is written to it, in the refresh function, the version of token_version in the database and in refresh_token is compared. The version of the token in the database changes when the password is changed.

  • @motiurrahman3023
    @motiurrahman3023 10 місяців тому

    Hello Sir, for /refresh API I can not pass the token via body it's asking for the user name what is the issue. @UseGuards(RefreshJwtAuthGuard)
    @Post("/refresh")
    async refreshToken(@Request() req: any) {
    //console.log(req.user);
    return await this.authService.refreshToken(req.user);
    }

  • @reihaxhiraj996
    @reihaxhiraj996 Рік тому +1

    why am i getting unauthroized 401 at 24:25 ,whyyyyyyyyyyyyyyy the the code is completely the same

    • @SakuraDev
      @SakuraDev  Рік тому

      Probably you missed out something. I shuold see it.

    • @Djika-ro2de
      @Djika-ro2de 10 місяців тому

      A little late to the party. If the code is same check out your postman/insomnia, maybe you're misnaming your field username, I've put email and probably because localstrategy only recognises that field it didn't work, my user object wasn't even available nor could I catch an error. Hope it helps

    • @RaphDaPinguFTW
      @RaphDaPinguFTW 9 місяців тому

      I had this problem as well, make sure your auth.service.ts has:
      bcrypt.compare(password, user.password))
      and not:
      bcrypt.compare(user.password, password))

    • @SakuraDev
      @SakuraDev  9 місяців тому

      @@RaphDaPinguFTW Yes the user.password must be on second argument.

  • @akdasa
    @akdasa 2 місяці тому

    You implemented it incorrectly. What should you do once refresh token is expired? How you can revoke refresh token if it compromised?

    • @SakuraDev
      @SakuraDev  2 місяці тому

      Once refresh token is expired we simply request a new login. a new login once in a week is not a big deal. To revoke a refresh token we can keep a blacklist in our database or configure redis for keeping them.

    • @akdasa
      @akdasa 2 місяці тому

      @SakuraDev What is the purpose of such "refresh token"? Just issue an access tokens for that period ( = Incorrect approach). Anyone who require regular authentication should burn in hell. Think about users with mobile phones.
      You should store the refresh token in the database. Why does it have to expire at all? Just keep issuing new access tokens using refresh token that never expire. If it is compromised, simply refresh (or delete) the refresh token, it will automatically log out all sessions associated with that refresh token.

    • @SakuraDev
      @SakuraDev  2 місяці тому

      Yeah, This is the approach we used in our real world projects. Thanks for bringing that to my attention.

    • @SakuraDev
      @SakuraDev  2 місяці тому

      And One Question, we usually use Redis for keeping tokens. Do you also use Redis for that or use something else?

  • @ne0nowy
    @ne0nowy 8 місяців тому

    `${process.env.jwt_secret}` is incorrect solution because it cause empty string as secret ;)

    • @SakuraDev
      @SakuraDev  8 місяців тому

      Yes, it was in incorrect