Confirmation tokens are often used to verify user email addresses or other sensitive information. In this guide, we’ll demonstrate how to create and decode confirmation tokens using JWTs in FastAPI.
Generating Confirmation Tokens
Python
import jwt
from fastapi import Depends, HTTPException
from app.models import User
def create_confirmation_token(user_id: int):
data = {"user_id": user_id}
token = jwt.encode(data, "your_secret_key", algorithm="HS256")
return token
Sending Confirmation Emails
Once you’ve generated a confirmation token, you can send it to the user’s email address in a confirmation email. The email should contain a link that includes the confirmation token.
Decoding Confirmation Tokens
Python
def decode_confirmation_token(token: str):
try:
data = jwt.decode(token, "your_secret_key", algorithms=["HS256"])
return data["user_id"]
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=400, detail="Confirmation token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=400, detail="Invalid confirmation token")
Verifying Confirmation Tokens
Python
@app.get("/confirm/{token}")
async def confirm_email(token: str, db: Session = Depends(get_db)):
try:
user_id = decode_confirmation_token(token)
user = await db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.is_verified = True
db.add(user)
await db.commit()
return {"message": "Email confirmed"}
except HTTPException as e:
raise e
Additional Factors
- Token Expiration: Set an expiration time for confirmation tokens to prevent abuse.
- Unique Tokens: Ensure that each confirmation token is unique.
- Security: Keep your secret key secret and use a strong algorithm for signing JWTs.
- Resend Options: Provide users with the option to resend the confirmation email if they don’t receive it.