FastAPI JWT Tutorial | How to add User Authentication
In this tutorial, we will walk you through the process of integrating JWT (JSON Web Tokens) with FastAPI to secure user authentication. If you want to add JWT authentication to your FastAPI application, this video is for you!
If you are new to FastAPI or JWT, don't worry. We will cover the basics and gradually move towards more advanced topics. You'll get to understand not only how to implement JWT but also why it is important. FastAPI JWT authentication is what you want to use for your JWT Python project
🎥 React + FastAPI: • How to build a React +...
🎥 AWS Lambda + FastAPI: • Deploy FastAPI on AWS ...
🎥 MongoDB + FastAPI: • Unlocking the Power of...
🎥 MySQL + FastAPI: • How to build a FastAPI...
🎥 PostgreSQL + FastAPI: • How to build a FastAPI...
===========================
🎓 Courses can be found:
FastAPI Beginner & Advanced: www.udemy.com/course/fastapi-...
Learn Chatbot Development: www.udemy.com/course/the-comp...
===========================
🛒 GEAR & RECOMMENDED BOOKS: kit.co/codingwithroby
👨💻 Hi, I am Eric!👨💻
Hey! I’m a seasoned developer and cloud enthusiast. I love sharing my knowledge and helping others to discover the exciting world of programming and cloud technologies. For more tutorials, tips, and tech magic, don’t forget to hit that subscribe button and ring the bell for notifications!
🙏 Support The Channel 🙏
If you found this tutorial helpful, please give it a thumbs up 👍, comment, and share it with your network 🌍
#fastapi #python #programming
Пікірлер: 95
Man, congratulations on your lessons. Here in Brazil, we find little information about this subject, and you are saving us.
@codingwithroby
5 ай бұрын
Awesome, thank you! I am happy to help
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!
@codingwithroby
Жыл бұрын
Glad I could help!
@8bitoverclocking932
Жыл бұрын
Agreed! I was literally starting this this morning but didn't see this vid until now. You have a new sub!
@codingwithroby
Жыл бұрын
Woot woot! Welcome friend 🙂
Very nice and structured video! Helped a lot, thanks!
@codingwithroby
7 ай бұрын
Great to hear! Glad you enjoyed it!
Thankyou for sharing the tutorial :)
@codingwithroby
10 ай бұрын
Of course, glad you are able to find value!
Thanks man for this tutorial. It was amazing well explained and really saved me :)
@codingwithroby
2 ай бұрын
You are sooo welcome! Cheers 🥂
Amazing tutorial. I really enjoyed it. thanks for the amazing explaination🙏
@codingwithroby
3 ай бұрын
Glad you enjoyed it! These types of comments keep me going, thank you 😊
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.
your fastapi course on udemy is amazing
@codingwithroby
7 ай бұрын
Yay! I am glad you enjoy it!!
hey, how i can get the token and save it in browser(how i can use oauth2) without using fastapi docs interface
I am created crud operation using fastapi and python,then I want implement jwt refresh token,pls give any idea
19:47 - I want to have a place holder for just the token and not the entire form. How to do that?
Can I download your code from this tutorial somewhere? Keep up the good work. Btw, very helpful turorial! Thank you so much.
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
@codingwithroby
10 ай бұрын
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
@codingwithroby
9 ай бұрын
Thank you! I would recommend using Redis or caching to do this :-)
hello , thanks for video, is it possible to share your setup to create this kind of content ? thanks advance
why we need then token after sign in if authorize user with username and password still
awesome! really looked for a good fastapi auth content. one question, as i'm trying to understand the authentication world. so every endpoint i want to be protected, should validate the user like is done at the end at the "/" endpoint? this how authentication is usually being done in backend apps? doesn't it add a very high time complexity for each request (to check for the use in the db, which can have many users)
@codingwithroby
10 ай бұрын
Hey friend! Well, you authenticate the first time after that you verify the token's data on each request. This is pretty much how all token based authentication works 🙂
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
9 ай бұрын
You are right! It's tough speaking in front of a camera, sometimes things just come out LOL
@ishan.girdhar
9 ай бұрын
@@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. 🤗
@codingwithroby
9 ай бұрын
You're the best! Thanks for pointing that out for future viewers 🙂
Hi, thank you for the tutorial, how do I define a route that is accessible only when an user is logged in?
@codingwithroby
9 ай бұрын
You will want to add dependency injection to "get_current_user"
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.
@codingwithroby
9 ай бұрын
Ohh not a bad idea, I will add it to my backlog of future videos 🙂
Hi Eric, Annotated is not supported in python 3.8 version could pls suggest alternative??
@codingwithroby
8 ай бұрын
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 your video. But do you know how I can integrate Clerk to my fast api project?
@codingwithroby
2 ай бұрын
Not as of right now sorry, I can look into making a video in the future on it 🙂
What tool do you use to record lectures. its just amazing
@codingwithroby
8 ай бұрын
Yo! thanks 🙂 I use a mirrorless camera for recording myself, heir PR40 for mircophone and camtashia for recording!
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
@codingwithroby
9 ай бұрын
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!
@codingwithroby
6 ай бұрын
You bet! Currently I do not for a KZread video, perhaps that could be a good addition to the Udemy course?
@rootifera
6 ай бұрын
@@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!
i watched many videos , you explained ,everything perfect , thank you so much , just watched it too late :( ,
@codingwithroby
6 ай бұрын
Glad it helped!
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?
@codingwithroby
11 ай бұрын
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.
Why did you make the get_current_user function async?
@codingwithroby
11 ай бұрын
It is used for dependency injection if you are wanting to find the current user signed in
@timbrap4693
11 ай бұрын
@@codingwithroby but is it necessary to make it async? There is no awaiting inside the function
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?
@codingwithroby
11 ай бұрын
Not when using Swagger - An alternative could be using Postman or another API Test platform and then you can reuse the JWT
@laszlomagyar3156
11 ай бұрын
@@codingwithroby Thank you!
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.
@codingwithroby
4 ай бұрын
Yeah - that's my bad, I don't have it anymore.
Keep going.
@codingwithroby
Жыл бұрын
Thank you, that’s the plan!
Fantastic video, can you share the Github repo?
@codingwithroby
11 ай бұрын
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 🙂
but we never used the bearer token or did we ?
@codingwithroby
4 ай бұрын
We did 🙂
Hey what ide theme is that?
@codingwithroby
7 ай бұрын
One dark pro extension on VS Code.
If some hack knows the secret key and the algorithm how can he authenticate? Doesn t the function get_current_user prevents that?
@codingwithroby
Ай бұрын
Well, hypothetically they can create the JWT from their own code then.
How do i connect it with frontend?
@codingwithroby
11 ай бұрын
Great question! Check out my full stack video : kzread.info/dash/bejne/Yq6WlM2omLzAebA.htmlsi=v_eDYYlytP04CNcj
how we integrate google auth with this?
@codingwithroby
11 ай бұрын
Hmm this sounds like a nice video idea!
@a.s8840
11 ай бұрын
@@codingwithroby Yes I am very curious to learn this ..I am following you udemy course
@a.s8840
11 ай бұрын
@@codingwithroby can you suggest me how can I integrate.😢😢
where i can get this code?
@codingwithroby
8 ай бұрын
I didn't make a repo before deleting the project - sorry 😞
Good content. Please look up how to pronounce "schema".
@codingwithroby
11 ай бұрын
Glad you enjoyed the content 🙂
Your code is fool proof. But I was wondering how did you map this with your finance app? Please let me know
@codingwithroby
9 ай бұрын
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
also upload link for source code
@codingwithroby
4 ай бұрын
Yeah - that's my bad, I don't have it anymore.
@hrushikeswarareddy251
4 ай бұрын
😅👍
4:45, How the hell do you unhash something, ?????
@codingwithroby
3 ай бұрын
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)
Background music is annoying
@codingwithroby
4 ай бұрын
Sorry my guy
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