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
Thank you for this! I m looking forward to the TypeORM tutorials for NestJS. :D
thnks dude! such a great video! i've learning so much w/ this!. Greetings from Brazil!
Thanks for watching. I am glad it was helpful and also I am so proud to have many subscribers from Brazil. 🌹
Thank you very much!!!
Thank you for this video! It was of great help for me.
glad it was helpful 🌷
Greetings from Brazil, amazing tutorial, helped me a lot!
Thanks. I am really happy to have you from Brazil. 🌹
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
i'm grateful for your videos ! Its simple and fast explanation what I ever see about oauth2
Glad you like them!
Thank you so much for this amazing video.
I'm really glad you like it 🙏
I really like how you teach these series ! Please build more authenticate and authorization NestJS app with key cloak 💥💥
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! 💪🌟
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?
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.
Thanks!
The content is beneficial.
Glad it was helpful!
Could you complete this by adding simple roles?
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
Yes, you can use different key for refresh token. Thanks for bringing that to my attention🌷
Thanks
Great work bro!
Thank you! Cheers!
what if the tokens were saved as http only tokens?
Thanks mate, you didn't mention how to generate the refresh token automatically with each request with nextjs for example!
amazing tutorial!! thank you for the video.. but i have a question how to implement dto on local strategy?
It would be great if you upload a video on integrating microservice with Nest.js using Kafka. Thanks!
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.
Congratulations Excellent Tutorial Thanks Sakura
Thanks for your nice feedback🙏
where does passport compare that payload is correct?, i mean if you decode jwt from bearer header, you should see if payload is correct.
hi, passport.js does it under the hood.
@@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
@@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
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).
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.
where and how we can store logged in user imformation like email, user_id, and role for further uses
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.
is it okay to return role in refresh token with access token? how to handle role also?
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.
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
Hi, thanks for bringing that to my attention. The solution to this problem is using different secret keys for access token and refresh token
good
Thanks
I'm still waiting for comprehensive Typeorm course😆
Can you prepare a dockerize tutorial that simulates dev and prod environment? Thames 👌
Sure, I'd be happy to help with that. I will do it.
You created JwtStrategy class and defined that in auth provider and you don't used from that. why?
we don't use jwtStrategy directly. I used it to create a jwt-guard and then use that guard to protect my APIs.
@@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?
It's falling APART and they won't stop it ALL from burning down over the 'message'
Everyone writes guides about jwt token so cool, but no one wrote down what to do if an attacker stole a refreshToken
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.
@@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.
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);
}
why am i getting unauthroized 401 at 24:25 ,whyyyyyyyyyyyyyyy the the code is completely the same
Probably you missed out something. I shuold see it.
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
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))
@@RaphDaPinguFTW Yes the user.password must be on second argument.
You implemented it incorrectly. What should you do once refresh token is expired? How you can revoke refresh token if it compromised?
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.
@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.
Yeah, This is the approach we used in our real world projects. Thanks for bringing that to my attention.
And One Question, we usually use Redis for keeping tokens. Do you also use Redis for that or use something else?
`${process.env.jwt_secret}` is incorrect solution because it cause empty string as secret ;)
Yes, it was in incorrect