Hashing and encryption are different things. A hash cannot be unhashed into its source data, but encrypted data can. This is important for passwords because it means even if your DB is compromised and your secret keys are leaked, it's still impossible for the attacker to figure out your users' plaintext passwords. If you were using encryption instead of hashing, then there's danger of leaking plaintext passwords in an attack. So hashing is the correct way to go, and bcrypt is a great choice for the hash method. I know this sounds like a minor nitpick, but when you're trying to teach people I think it's important to be clear about terminology and the reason for certain choices. If you don't know the distinction between hashing and encryption, you're more likely to implement a flawed authentication system in your project (and I've seen it in the wild on multiple occasions). Thanks for the content!
Nice tutorial. But it would be awesome if you include a link to a repo. It's not because I don't want to type but I want to see multiple file at the same time while watching your video. Thanks anyway.
Hi, did a little bit more for fun: delete users, get all users etc. Then I make delete with user_dependency, so only users authenticated can delete. And I tried to delete the user validated and worked (I guess till 20 minuts it will work). Nice tutorial!
Super helpful! just 1 small request, let's not call it, un-hash. You can't un-hash a hash. Hashing is one way encryption. You can match the hash with the user provided password and match it with the hash already stored in database.
@@codingwithroby Hey, I understand. It’s hard. I just wanted to drop a comment to avoid any misunderstanding for the viewers. Not a reflection on you. Even though I have bought your course on Udemy, I am still watching your free videos here. 🤗
I'm having a problem in the swagger the Authorize button is performing the call towards the endpoint /token (which does not exist) instead that /auth/token as shown at 19:50. I cannot understand why.
Hey Eric my question in my mind is always how to keep these token on the frontend, I send access token an response header and in JSON format and don't give refresh token instead set it as a httponly cookie. In frontend I keep it in context API and to make sure if user is logged in or not for each 401 message I try to send request to refresh endpoint and in this way my cookie has been read by fast API and again I keep it in context API in frontend which is nextjs What do you think of this? What is the best practice? I want to know your opinion
Hey great question! The best way is to save the token inside your local or session storage on your frontend. This means you can call the current token whenever it is needed. When sending the token always make sure to have FastAPI verify the token. If it is successful than the token works, proceed as normal. If the token does not work either: A) Delete token on FE and redirect to login page again (so they can resign in) B) (Much more advanced) Send a new token from the BE based on other factors if you are tracking them (IP addresses location, etc) to verify it is the correct user outside of just the token
Gracias amigo!! This video is very informative, your explanation are super clear, I would ask about the expiration time an automatically refresh it, refresh token or smt, is it store on db? Thx again for your time
Thanks for the tutorial. Could you suggest some way to mask/hide the SECRET_KEY and ALGORITHM values? One of my motivation of using JWT is to avoid hard-code some password or secret in source code/config file. Thanks.
Hi Eric, thanks for the video. I just finished your FastApi Udemy course and writing a small API for inventory management. I'm trying to get Refresh token to work but couldn't figure it out yet. Do you have any plans to make a video about using Refresh tokens? Thanks!
@@codingwithroby hey Eric! yeah that would be amazing! I finally made the refresh token work (I still need to test) but it would be great to see how you do it so I can improve my code and especially understanding of the tokens. Thanks!
The import statement in the auth file: from datetime import timedelta, datetime from typing import Annotated from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from sqlalchemy.orm import Session from starlette import status from database import SessionLocal from models import Users from passlib.context import CryptContext from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer from jose import jwt, JWTError
Hey Eric this video is awesome. Just now i am implementing some my own project and this information was so useful! Is it possible to implement "logout" functionality?
Hi friend! This is complicated and not complicated at the exact same time 🥲 JWT's are very popular because you do not need a database for validation each time and they are completely stateless. This means the backend does not know what the JWT is outside of authorizing the original intent. However, each JWT DOES have an expiration date, lets for example say 20 minutes. The absolute best way to create a log out system is to create a blacklist system for JWT's. For example using in-memory (like Redis - if you do not know Redis there is a video coming verrrrryyyy soon) store the JWT there, set the ttl to expire when the JWT expires, and compare new requests to this list of blacklist JWT's to either approve to deny.
I misspoke (being on camera is hard!) - Once a password is hashed, you rehash the next "plain" password to see if the values match. Example (but always use verify method): hashed_password == hashed(plain_text_password)
Man, congratulations on your lessons. Here in Brazil, we find little information about this subject, and you are saving us.
Awesome, thank you! I am happy to help
you can read the docs online as well.
Hashing and encryption are different things. A hash cannot be unhashed into its source data, but encrypted data can.
This is important for passwords because it means even if your DB is compromised and your secret keys are leaked, it's still impossible for the attacker to figure out your users' plaintext passwords.
If you were using encryption instead of hashing, then there's danger of leaking plaintext passwords in an attack. So hashing is the correct way to go, and bcrypt is a great choice for the hash method.
I know this sounds like a minor nitpick, but when you're trying to teach people I think it's important to be clear about terminology and the reason for certain choices. If you don't know the distinction between hashing and encryption, you're more likely to implement a flawed authentication system in your project (and I've seen it in the wild on multiple occasions).
Thanks for the content!
Nice tutorial. But it would be awesome if you include a link to a repo. It's not because I don't want to type but I want to see multiple file at the same time while watching your video. Thanks anyway.
Wow the timing, this is literally what i was just trying to figure out! Thanks!
Glad I could help!
Agreed! I was literally starting this this morning but didn't see this vid until now. You have a new sub!
Woot woot! Welcome friend 🙂
I was missing just one line and your video helped expose my issues. Thanks friend. Look forward to seeing more.
Nice work! Welcome 🤗
Hi, did a little bit more for fun: delete users, get all users etc. Then I make delete with user_dependency, so only users authenticated can delete. And I tried to delete the user validated and worked (I guess till 20 minuts it will work). Nice tutorial!
haha awesome! I appreciate the kind words on the tutorial 🙂
your fastapi course on udemy is amazing
Yay! I am glad you enjoy it!!
Very nice and structured video! Helped a lot, thanks!
Great to hear! Glad you enjoyed it!
Super helpful! just 1 small request, let's not call it, un-hash. You can't un-hash a hash. Hashing is one way encryption. You can match the hash with the user provided password and match it with the hash already stored in database.
You are right! It's tough speaking in front of a camera, sometimes things just come out LOL
@@codingwithroby Hey, I understand. It’s hard. I just wanted to drop a comment to avoid any misunderstanding for the viewers. Not a reflection on you.
Even though I have bought your course on Udemy, I am still watching your free videos here. 🤗
You're the best! Thanks for pointing that out for future viewers 🙂
I'm having a problem in the swagger the Authorize button is performing the call towards the endpoint /token (which does not exist) instead that /auth/token as shown at 19:50. I cannot understand why.
Amazing tutorial. I really enjoyed it. thanks for the amazing explaination🙏
Glad you enjoyed it! These types of comments keep me going, thank you 😊
19:47 - I want to have a place holder for just the token and not the entire form. How to do that?
Thanks man for this tutorial. It was amazing well explained and really saved me :)
You are sooo welcome! Cheers 🥂
Thankyou for sharing the tutorial :)
Of course, glad you are able to find value!
Hey Eric my question in my mind is always how to keep these token on the frontend, I send access token an response header and in JSON format and don't give refresh token instead set it as a httponly cookie.
In frontend I keep it in context API and to make sure if user is logged in or not for each 401 message I try to send request to refresh endpoint and in this way my cookie has been read by fast API and again I keep it in context API in frontend which is nextjs
What do you think of this?
What is the best practice?
I want to know your opinion
Hey great question! The best way is to save the token inside your local or session storage on your frontend. This means you can call the current token whenever it is needed.
When sending the token always make sure to have FastAPI verify the token. If it is successful than the token works, proceed as normal. If the token does not work either:
A) Delete token on FE and redirect to login page again (so they can resign in)
B) (Much more advanced) Send a new token from the BE based on other factors if you are tracking them (IP addresses location, etc) to verify it is the correct user outside of just the token
Very cool thank you !
Thanks!
Can I download your code from this tutorial somewhere? Keep up the good work.
Btw, very helpful turorial! Thank you so much.
hey, how i can get the token and save it in browser(how i can use oauth2) without using fastapi docs interface
Hey what ide theme is that?
One dark pro extension on VS Code.
i watched many videos , you explained ,everything perfect , thank you so much , just watched it too late :( ,
Glad it helped!
What tool do you use to record lectures. its just amazing
Yo! thanks 🙂 I use a mirrorless camera for recording myself, heir PR40 for mircophone and camtashia for recording!
Why did you make the get_current_user function async?
It is used for dependency injection if you are wanting to find the current user signed in
@@codingwithroby but is it necessary to make it async? There is no awaiting inside the function
I am created crud operation using fastapi and python,then I want implement jwt refresh token,pls give any idea
but we never used the bearer token or did we ?
We did 🙂
Thanks for your video. But do you know how I can integrate Clerk to my fast api project?
Not as of right now sorry, I can look into making a video in the future on it 🙂
Hi, thank you for the tutorial, how do I define a route that is accessible only when an user is logged in?
You will want to add dependency injection to "get_current_user"
hello , thanks for video, is it possible to share your setup to create this kind of content ? thanks advance
Gracias amigo!! This video is very informative, your explanation are super clear, I would ask about the expiration time an automatically refresh it, refresh token or smt, is it store on db? Thx again for your time
Thank you! I would recommend using Redis or caching to do this :-)
Hi Eric, Annotated is not supported in python 3.8 version could pls suggest alternative??
I would recommend upgrading Python, but you do not need to using Annotated. You can pass the Dependency right in the parameter itself.
Thanks for the tutorial. Could you suggest some way to mask/hide the SECRET_KEY and ALGORITHM values? One of my motivation of using JWT is to avoid hard-code some password or secret in source code/config file. Thanks.
You can add to a .env file locally and then store in a secret manager on the cloud.
Thanks for the tutorial! Can you make a sequal on token rotation. How to refresh access token seamlessly without logging the user out. Thank you.
Ohh not a bad idea, I will add it to my backlog of future videos 🙂
Really quick, what if the user is logged in and goes to the homepage, I want to redirect them to another page since they're already logged in
You will want the Front End to handle the redirects.
Hi Eric, thanks for the video. I just finished your FastApi Udemy course and writing a small API for inventory management. I'm trying to get Refresh token to work but couldn't figure it out yet. Do you have any plans to make a video about using Refresh tokens? Thanks!
You bet! Currently I do not for a RUclips video, perhaps that could be a good addition to the Udemy course?
@@codingwithroby hey Eric! yeah that would be amazing! I finally made the refresh token work (I still need to test) but it would be great to see how you do it so I can improve my code and especially understanding of the tokens. Thanks!
why we need then token after sign in if authorize user with username and password still
Because if user tries to login second time no password is needed...
What about blacklisting token??
Yeah - you'll probably want to do that or make the expire shorter.
@ can you tell me how we can create a logout route where we can blacklist token?
@@uchihaobito723 Fairly long topic. I'll add it to my backlist of items to create videos on 🙂
@ its for my project. So please consider it
how we integrate google auth with this?
Hmm this sounds like a nice video idea!
@@codingwithroby Yes I am very curious to learn this ..I am following you udemy course
@@codingwithroby can you suggest me how can I integrate.😢😢
@@codingwithroby i also got intrest for it, hope you create a video on it soon
The import statement in the auth file:
from datetime import timedelta, datetime
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from starlette import status
from database import SessionLocal
from models import Users
from passlib.context import CryptContext
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from jose import jwt, JWTError
thanks for the vid. don't see what's the point of the music in the background all the way through? if I want to listen to music, I put on some music.
I've been getting better and learning RUclips. Future videos don't have music during coding.
Hey Eric this video is awesome. Just now i am implementing some my own project and this information was so useful! Is it possible to implement "logout" functionality?
Hi friend! This is complicated and not complicated at the exact same time 🥲
JWT's are very popular because you do not need a database for validation each time and they are completely stateless. This means the backend does not know what the JWT is outside of authorizing the original intent. However, each JWT DOES have an expiration date, lets for example say 20 minutes.
The absolute best way to create a log out system is to create a blacklist system for JWT's. For example using in-memory (like Redis - if you do not know Redis there is a video coming verrrrryyyy soon) store the JWT there, set the ttl to expire when the JWT expires, and compare new requests to this list of blacklist JWT's to either approve to deny.
I converted your tutorial to async sqlalchemy.
Nice work!
If I login then refresh the page I need to login again to access the login required features. Why is that? Is there a way to avoid this?
Not when using Swagger - An alternative could be using Postman or another API Test platform and then you can reuse the JWT
@@codingwithroby Thank you!
Fantastic video, can you share the Github repo?
Hey friend! Thanks for the suggestion. As of now I have not added public repositories. I am planning on doing so in the near future 🙂
How do i connect it with frontend?
Great question! Check out my full stack video : ruclips.net/video/0zb2kohYZIM/видео.htmlsi=v_eDYYlytP04CNcj
where i can get this code?
I didn't make a repo before deleting the project - sorry 😞
If some hack knows the secret key and the algorithm how can he authenticate? Doesn t the function get_current_user prevents that?
Well, hypothetically they can create the JWT from their own code then.
Hi Eric,
Just from few weeks back i have started watching your videos are awesome,
i think it will be helpful if you could post the code.
Yeah - that's my bad, I don't have it anymore.
4:45, How the hell do you unhash something, ?????
I misspoke (being on camera is hard!) - Once a password is hashed, you rehash the next "plain" password to see if the values match.
Example (but always use verify method): hashed_password == hashed(plain_text_password)
Your code is fool proof. But I was wondering how did you map this with your finance app? Please let me know
You're the best, thank you! The best way is to keep the token in the React SessionStorage or LocalStorage and send it as a header within the request
thanks alot
You're welcome!
Keep going.
Thank you, that’s the plan!
Good content. Please look up how to pronounce "schema".
Glad you enjoyed the content 🙂
also upload link for source code
Yeah - that's my bad, I don't have it anymore.
😅👍
The background music was unnecessary.
It’s not there for future videos
@@codingwithroby Thank you brother. Now that you replied back, I am feeling bad for being rude. Great work by the way. Learned from you. ❤
@@alexpyofficial lol all good dude
Background music is annoying
Sorry my guy
turn down your music it's annoying
I removed it in future videos.