Junior — Middle
What methods are used to ensure security in FastAPI?
sobes.tech AI
Answer from AI
FastAPI ensures security through several methods:
- Authentication and Authorization: Using OAuth2 with JWT tokens or basic authentication to verify users.
- Security Dependencies: FastAPI allows injecting dependencies that check access rights before executing endpoints.
- Data Validation: Thanks to Pydantic, incoming data to the API is validated, reducing the risk of vulnerabilities.
- HTTPS: It is recommended to run the application behind a proxy server supporting HTTPS to protect data during transmission.
- CORS: Configuring Cross-Origin Resource Sharing to restrict access to the API from certain domains.
Example of using OAuth2 with JWT in FastAPI:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def fake_decode_token(token):
# Logic for decoding and verifying the token should be here
if token == "fake-super-secret-token":
return {"sub": "user"}
raise HTTPException(status_code=401, detail="Invalid token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
return user
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_user