FastAPI JWT Tutorial | How to add User Authentication

Поделиться
HTML-код
  • Опубликовано: 26 дек 2024

Комментарии •

  • @breno-codes1633
    @breno-codes1633 10 месяцев назад +10

    Man, congratulations on your lessons. Here in Brazil, we find little information about this subject, and you are saving us.

  • @justin7509
    @justin7509 24 дня назад +3

    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!

  • @lonehayena
    @lonehayena 11 месяцев назад +44

    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.

  • @ryanschaefer4847
    @ryanschaefer4847 Год назад +8

    Wow the timing, this is literally what i was just trying to figure out! Thanks!

    • @codingwithroby
      @codingwithroby  Год назад +1

      Glad I could help!

    • @8bitoverclocking932
      @8bitoverclocking932 Год назад +1

      Agreed! I was literally starting this this morning but didn't see this vid until now. You have a new sub!

    • @codingwithroby
      @codingwithroby  Год назад +1

      Woot woot! Welcome friend 🙂

  • @Gwittdog
    @Gwittdog Месяц назад

    I was missing just one line and your video helped expose my issues. Thanks friend. Look forward to seeing more.

  • @jordiprim2668
    @jordiprim2668 Месяц назад

    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!

    • @codingwithroby
      @codingwithroby  Месяц назад

      haha awesome! I appreciate the kind words on the tutorial 🙂

  • @edderleonardo
    @edderleonardo Год назад +2

    your fastapi course on udemy is amazing

  • @JuliusThePianoGuy
    @JuliusThePianoGuy Год назад +1

    Very nice and structured video! Helped a lot, thanks!

  • @ishan.girdhar
    @ishan.girdhar Год назад +4

    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
      @codingwithroby  Год назад +2

      You are right! It's tough speaking in front of a camera, sometimes things just come out LOL

    • @ishan.girdhar
      @ishan.girdhar Год назад +1

      @@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
      @codingwithroby  Год назад +1

      You're the best! Thanks for pointing that out for future viewers 🙂

  • @vincenzobuonvino5860
    @vincenzobuonvino5860 Год назад

    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.

  • @jacobwilsonmwale1674
    @jacobwilsonmwale1674 8 месяцев назад +1

    Amazing tutorial. I really enjoyed it. thanks for the amazing explaination🙏

    • @codingwithroby
      @codingwithroby  8 месяцев назад

      Glad you enjoyed it! These types of comments keep me going, thank you 😊

  • @thegrind9628
    @thegrind9628 11 месяцев назад

    19:47 - I want to have a place holder for just the token and not the entire form. How to do that?

  • @herozero777
    @herozero777 7 месяцев назад

    Thanks man for this tutorial. It was amazing well explained and really saved me :)

  • @anuj7286
    @anuj7286 Год назад +2

    Thankyou for sharing the tutorial :)

  • @karacan2469
    @karacan2469 Год назад +2

    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
      @codingwithroby  Год назад +1

      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

  • @davidl3383
    @davidl3383 21 день назад

    Very cool thank you !

  • @rstiekema
    @rstiekema 6 месяцев назад

    Can I download your code from this tutorial somewhere? Keep up the good work.
    Btw, very helpful turorial! Thank you so much.

  • @gleb29
    @gleb29 Год назад

    hey, how i can get the token and save it in browser(how i can use oauth2) without using fastapi docs interface

  • @diezitrone_111
    @diezitrone_111 Год назад +1

    Hey what ide theme is that?

  • @queenqueents-l9s
    @queenqueents-l9s 11 месяцев назад +1

    i watched many videos , you explained ,everything perfect , thank you so much , just watched it too late :( ,

  • @learnapplybuild
    @learnapplybuild Год назад

    What tool do you use to record lectures. its just amazing

    • @codingwithroby
      @codingwithroby  Год назад

      Yo! thanks 🙂 I use a mirrorless camera for recording myself, heir PR40 for mircophone and camtashia for recording!

  • @timbrap4693
    @timbrap4693 Год назад

    Why did you make the get_current_user function async?

    • @codingwithroby
      @codingwithroby  Год назад

      It is used for dependency injection if you are wanting to find the current user signed in

    • @timbrap4693
      @timbrap4693 Год назад

      @@codingwithroby but is it necessary to make it async? There is no awaiting inside the function

  • @sowmiyapannerselvam997
    @sowmiyapannerselvam997 8 месяцев назад

    I am created crud operation using fastapi and python,then I want implement jwt refresh token,pls give any idea

  • @mudassiraqeel8604
    @mudassiraqeel8604 9 месяцев назад +1

    but we never used the bearer token or did we ?

  • @4crazibility75
    @4crazibility75 7 месяцев назад

    Thanks for your video. But do you know how I can integrate Clerk to my fast api project?

    • @codingwithroby
      @codingwithroby  7 месяцев назад

      Not as of right now sorry, I can look into making a video in the future on it 🙂

  • @LamNguyen-hw9lq
    @LamNguyen-hw9lq Год назад

    Hi, thank you for the tutorial, how do I define a route that is accessible only when an user is logged in?

    • @codingwithroby
      @codingwithroby  Год назад

      You will want to add dependency injection to "get_current_user"

  • @nulops
    @nulops 11 месяцев назад

    hello , thanks for video, is it possible to share your setup to create this kind of content ? thanks advance

  • @dannisisgt
    @dannisisgt Год назад +1

    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
      @codingwithroby  Год назад

      Thank you! I would recommend using Redis or caching to do this :-)

  • @appallasuryanarayanababu5074
    @appallasuryanarayanababu5074 Год назад

    Hi Eric, Annotated is not supported in python 3.8 version could pls suggest alternative??

    • @codingwithroby
      @codingwithroby  Год назад +1

      I would recommend upgrading Python, but you do not need to using Annotated. You can pass the Dependency right in the parameter itself.

  • @williamyoutube368
    @williamyoutube368 3 месяца назад

    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.

    • @codingwithroby
      @codingwithroby  3 месяца назад

      You can add to a .env file locally and then store in a secret manager on the cloud.

  • @ModernStockPortfolioTracker
    @ModernStockPortfolioTracker Год назад

    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
      @codingwithroby  Год назад

      Ohh not a bad idea, I will add it to my backlog of future videos 🙂

  • @Ken-ix7ms
    @Ken-ix7ms Год назад

    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
      @codingwithroby  Год назад +1

      You will want the Front End to handle the redirects.

  • @rootifera
    @rootifera 11 месяцев назад

    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
      @codingwithroby  11 месяцев назад +1

      You bet! Currently I do not for a RUclips video, perhaps that could be a good addition to the Udemy course?

    • @rootifera
      @rootifera 11 месяцев назад

      @@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!

  • @marsitschool9495
    @marsitschool9495 5 месяцев назад

    why we need then token after sign in if authorize user with username and password still

    • @sandeshvora
      @sandeshvora 4 месяца назад

      Because if user tries to login second time no password is needed...

  • @uchihaobito723
    @uchihaobito723 Месяц назад

    What about blacklisting token??

    • @codingwithroby
      @codingwithroby  Месяц назад

      Yeah - you'll probably want to do that or make the expire shorter.

    • @uchihaobito723
      @uchihaobito723 Месяц назад

      @ can you tell me how we can create a logout route where we can blacklist token?

    • @codingwithroby
      @codingwithroby  Месяц назад +1

      @@uchihaobito723 Fairly long topic. I'll add it to my backlist of items to create videos on 🙂

    • @uchihaobito723
      @uchihaobito723 Месяц назад

      @ its for my project. So please consider it

  • @a.s8840
    @a.s8840 Год назад +1

    how we integrate google auth with this?

    • @codingwithroby
      @codingwithroby  Год назад +1

      Hmm this sounds like a nice video idea!

    • @a.s8840
      @a.s8840 Год назад

      @@codingwithroby Yes I am very curious to learn this ..I am following you udemy course

    • @a.s8840
      @a.s8840 Год назад

      @@codingwithroby can you suggest me how can I integrate.😢😢

    • @OneKenyan
      @OneKenyan 2 месяца назад

      @@codingwithroby i also got intrest for it, hope you create a video on it soon

  • @marteinngumundsson8086
    @marteinngumundsson8086 9 месяцев назад +1

    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

  • @rainymatch
    @rainymatch 3 месяца назад

    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.

    • @codingwithroby
      @codingwithroby  3 месяца назад

      I've been getting better and learning RUclips. Future videos don't have music during coding.

  • @vicotrshysko6761
    @vicotrshysko6761 Год назад +1

    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
      @codingwithroby  Год назад +1

      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.

  • @default_youtube_profile
    @default_youtube_profile 4 месяца назад

    I converted your tutorial to async sqlalchemy.

  • @laszlomagyar3156
    @laszlomagyar3156 Год назад

    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
      @codingwithroby  Год назад +1

      Not when using Swagger - An alternative could be using Postman or another API Test platform and then you can reuse the JWT

    • @laszlomagyar3156
      @laszlomagyar3156 Год назад

      @@codingwithroby Thank you!

  • @LiftAndC0de
    @LiftAndC0de Год назад

    Fantastic video, can you share the Github repo?

    • @codingwithroby
      @codingwithroby  Год назад +1

      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 🙂

  • @ERYE
    @ERYE Год назад

    How do i connect it with frontend?

    • @codingwithroby
      @codingwithroby  Год назад

      Great question! Check out my full stack video : ruclips.net/video/0zb2kohYZIM/видео.htmlsi=v_eDYYlytP04CNcj

  • @Nau-uc9tk
    @Nau-uc9tk Год назад

    where i can get this code?

    • @codingwithroby
      @codingwithroby  Год назад

      I didn't make a repo before deleting the project - sorry 😞

  • @amiltonmoreira2341
    @amiltonmoreira2341 7 месяцев назад

    If some hack knows the secret key and the algorithm how can he authenticate? Doesn t the function get_current_user prevents that?

    • @codingwithroby
      @codingwithroby  7 месяцев назад

      Well, hypothetically they can create the JWT from their own code then.

  • @sivadevil4845
    @sivadevil4845 10 месяцев назад

    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
      @codingwithroby  10 месяцев назад

      Yeah - that's my bad, I don't have it anymore.

  • @nawaraj.karkee
    @nawaraj.karkee 8 месяцев назад

    4:45, How the hell do you unhash something, ?????

    • @codingwithroby
      @codingwithroby  8 месяцев назад

      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)

  • @chikkivenu6632
    @chikkivenu6632 Год назад

    Your code is fool proof. But I was wondering how did you map this with your finance app? Please let me know

    • @codingwithroby
      @codingwithroby  Год назад

      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

  • @Imperialcodex1
    @Imperialcodex1 3 месяца назад +1

    thanks alot

  • @suen-tech
    @suen-tech Год назад +1

    Keep going.

  • @Gladius000
    @Gladius000 Год назад +1

    Good content. Please look up how to pronounce "schema".

  • @hrushikeswarareddy251
    @hrushikeswarareddy251 10 месяцев назад

    also upload link for source code

  • @alexpyofficial
    @alexpyofficial 4 месяца назад +1

    The background music was unnecessary.

    • @codingwithroby
      @codingwithroby  4 месяца назад +1

      It’s not there for future videos

    • @alexpyofficial
      @alexpyofficial 4 месяца назад

      @@codingwithroby Thank you brother. Now that you replied back, I am feeling bad for being rude. Great work by the way. Learned from you. ❤

    • @codingwithroby
      @codingwithroby  4 месяца назад

      @@alexpyofficial lol all good dude

  • @kompalalokesh5586
    @kompalalokesh5586 10 месяцев назад

    Background music is annoying

  • @NightSwamp
    @NightSwamp 4 месяца назад

    turn down your music it's annoying