Quickly Authenticate Users with FastAPI and Token Authentication
Authentication is a crucial aspect of web application development. FastAPI, a modern web framework for building APIs with Python, provides an efficient way to authenticate users using token authentication. Token authentication involves the use of a token, usually a long string of characters, to verify the identity of a user.
Here’s how you can quickly authenticate users with FastAPI and token authentication:
Step 1: Install FastAPI
First, you need to install FastAPI. You can do this by using pip, the package installer for Python:
pip install fastapi
Step 2: Create a User Model
Next, create a user model that will store the user’s data, including their username and password. This model will be used for authentication:
from pydantic import BaseModel
class User(BaseModel):
username: str
password: str
Step 3: Generate a Token for Authentication
Using FastAPI, you can generate a token for authentication by using the JWT (JSON Web Tokens) library. This token will be used to verify the identity of the user:
import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# Use the username and password to authenticate the user
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Generate and return the token
token = create_access_token(data={"sub": user.username})
return {"access_token": token, "token_type": "bearer"}
Step 4: Protect API Endpoints with Authentication
Finally, you can protect your API endpoints by using the generated token for authentication. This will ensure that only authenticated users have access to specific resources:
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
By following these steps, you can quickly authenticate users with FastAPI and token authentication, ensuring that your web application is secure and only accessible to authorized users.
I'm sure this is helpful for a lot of new developers, but bare metal?
Гашиш в русском переводе, норм перевод
Thanks for video, and line by line explanation .. helpful for the user, using the OAUTH for first time.
Awesome, but i need second part, where is it?
from what I previously understand, first user login with username and password from login form and gets jwt token, second user send that jwt token to protected api routes, middleware extract the token from header and check if it is valid or not and decides to continue or stop the request. But the logic in FastAPI is a bit complicated. why do I need to pass again the username and password to access every protected routes?
Thanks for the video.
in BaseModel classes you should use :
username: Optional[str] = None
instead of
username: str or None = None
Thank you Tim for teaching and sharing.
To all, study, take breaks, apply knowledge and understanding, keep learning, before you know it your understanding is increasing and becomes comprehensible overtime.
How to install fastapi with out internet
Is possible to create with Oauth a role and permission model similar to RBAC?
How to test the same on Postman instead of Swagger?
why dont you just tell me this is an example on their documen.. waste damn time
thank you very much
got stuck on the openssl rannd -hex 32 bit. installed pyopenssl. pip list shows its installed. terminal says there is no such module. tried to add it to path but couldnt find the file for it.
If i cant even follow a tutorial , should i just give up on programming? i swear to god nothing ever works when i try and do it
But is there some info of path login , logout, signup?
im getting an error of "'openssl' is not recognized as an internal or external command,
operable program or batch file." while creating Secret Key
aweful video!
great video thank you Tim .
I have facing a problem in line 98 where it says db is not defined I don't really see db written or defined in your code but I see that we have named it fake_db. so what is happening ?
Is there a second part?
Would the same logic apply if I'd use Templates (jinja2) to display a frontend?