close
close
send a jwt in a header fastapi

send a jwt in a header fastapi

3 min read 07-12-2024
send a jwt in a header fastapi

This article provides a comprehensive guide on how to securely send JSON Web Tokens (JWTs) in HTTP headers using FastAPI. We'll cover the essential steps, best practices, and security considerations to ensure your application remains robust and protected.

Why Use JWTs?

JSON Web Tokens are a compact, self-contained way to transmit information between parties as a JSON object. They're ideal for authentication and authorization in microservices and APIs because they:

  • Reduce database hits: After initial authentication, you don't need to constantly query a database to verify user identity.
  • Improve scalability: JWTs are stateless, meaning they don't rely on server-side sessions, which simplifies scaling your application.
  • Enhance security: When properly implemented, JWTs offer a secure method for transmitting sensitive information.

Setting up Your FastAPI Project

First, ensure you have FastAPI and its dependencies installed. You can use pip:

pip install fastapi uvicorn PyJWT

We'll use the PyJWT library for JWT handling.

Generating and Verifying JWTs

Let's create a simple function to generate a JWT. This example uses a secret key – in a production environment, store this securely, ideally using environment variables.

import jwt
from datetime import datetime, timedelta

SECRET_KEY = "your-secret-key-here" # REPLACE WITH A STRONG SECRET KEY

def create_jwt(payload):
    """Generates a JWT."""
    payload['exp'] = datetime.utcnow() + timedelta(minutes=30) # JWT expiration time
    encoded_jwt = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
    return encoded_jwt

def decode_jwt(token):
    """Verifies and decodes a JWT."""
    try:
        decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        return decoded
    except jwt.ExpiredSignatureError:
        return None  # or raise an exception
    except jwt.InvalidTokenError:
        return None # or raise an exception

This code defines two functions: create_jwt which generates a JWT with an expiration time of 30 minutes, and decode_jwt which verifies and decodes the token. Remember to replace "your-secret-key-here" with a strong, randomly generated secret key.

FastAPI Implementation: Authentication Endpoint

Now let's create a FastAPI endpoint to generate JWTs:

from fastapi import FastAPI, Depends, HTTPException, Header
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class User(BaseModel):
    username: str

@app.post("/token")
async def login(user: User):
    #  In a real application, this would authenticate against a database
    #  This is a simplified example for demonstration purposes.
    if user.username == "admin":
        jwt_token = create_jwt({"sub": user.username})
        return {"access_token": jwt_token, "token_type": "Bearer"}
    raise HTTPException(status_code=401, detail="Incorrect username or password")


@app.get("/items/")
async def read_items(token: str = Header(...)):
    decoded_token = decode_jwt(token)
    if decoded_token:
        return {"items": [{"name": "Item A"}, {"name": "Item B"}]}
    else:
        raise HTTPException(status_code=401, detail="Invalid or expired token")

This code defines two endpoints: /token for obtaining a JWT after successful authentication (simplified here), and /items/ which requires a valid JWT in the Authorization header.

Sending the JWT in the Header

To access the /items/ endpoint, you need to send the JWT in the Authorization header like this:

curl -X GET "http://localhost:8000/items/" -H "Authorization: Bearer <your_jwt_token>"

Replace <your_jwt_token> with the JWT obtained from the /token endpoint.

Security Best Practices

  • Strong Secret Key: Use a long, randomly generated secret key. Never hardcode this in your application; use environment variables.
  • HTTPS: Always use HTTPS to encrypt communication between the client and server.
  • Token Expiration: Set a reasonable expiration time for your JWTs to limit the impact of stolen tokens.
  • Refresh Tokens: Consider using refresh tokens to allow users to extend their session without repeatedly logging in.
  • Input Validation: Sanitize and validate all user inputs to prevent injection attacks.

Conclusion

This comprehensive guide demonstrates how to seamlessly integrate JWT authentication into your FastAPI application. By following these steps and security best practices, you can create a secure and efficient API for your applications. Remember that the authentication logic in this example is simplified for demonstration purposes. In a real-world application, you'll need a robust authentication system, likely integrating with a database to manage users and their credentials.

Related Posts


Popular Posts