FastAPI Authentication JWT
FastAPI Authentication with JWT: A Beginner’s Guide
In this tutorial, we will explore how to implement authentication in a FastAPI application using JSON Web Tokens (JWT). JWT is a popular authentication mechanism that allows users to access protected routes by providing a token that contains their credentials. By the end of this tutorial, you will have a basic understanding of how to implement JWT authentication in your FastAPI application.
Installing Required Libraries
To get started with JWT authentication in FastAPI, we need to install the required libraries. We will need to install `fastapi`, `uvicorn`, and `python-jose` libraries. The `python-jose` library provides functions for working with JWT tokens.
pip install fastapi uvicorn python-jose
Creating a FastAPI Application
Next, we create a new FastAPI application. We will define a simple application with a single route that returns a welcome message.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI"}
Generating JWT Tokens
To generate JWT tokens, we will use the `python-jose` library. We will create a function that takes a user’s credentials and returns a JWT token.
from jose import jwt
from datetime import datetime, timedelta
def generate_token(user_id: str):
payload = {
"exp": datetime.utcnow() + timedelta(minutes=30),
"iat": datetime.utcnow(),
"sub": user_id
}
return jwt.encode(payload, "secret_key", algorithm="HS256")
Implementing Authentication
Next, we will implement authentication in our FastAPI application. We will create a function that checks if a user is authenticated by verifying their JWT token.
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Depends, HTTPException
security = HTTPBearer()
def get_current_user(token: HTTPAuthorizationCredentials = Depends(security)):
try:
payload = jwt.decode(token.credentials, "secret_key", algorithms=["HS256"])
return payload["sub"]
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=401,
detail="Token has expired"
)
except jwt.InvalidTokenError:
raise HTTPException(
status_code=401,
detail="Invalid token"
)
Protecting Routes with Authentication
Finally, we will protect our routes with authentication. We will use the `get_current_user` function to check if a user is authenticated before allowing them to access a protected route.
@app.get("/protected")
def read_protected(user_id: str = Depends(get_current_user)):
return {"message": f"Hello, {user_id}"}
Testing the Application
To test our application, we will use a tool like `curl` to send requests to our protected route. First, we need to generate a JWT token using the `generate_token` function.
curl -X GET \
http://localhost:8000/protected \
-H 'Authorization: Bearer '
Conclusion
In this tutorial, we have implemented JWT authentication in a FastAPI application. We have created a function to generate JWT tokens, implemented authentication, and protected our routes with authentication. By following this tutorial, you should now have a basic understanding of how to implement JWT authentication in your FastAPI application.