Here is an example of how you could implement an endpoint in FastAPI that authenticates a user using an external OAuth2 server using a bearer token:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from typing import Optional
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="external-oauth2-server.com/token")
@app.get("/protected-route")
async def protected_route(token: str = Depends(oauth2_scheme)):
# Verify the token with the external OAuth2 server
# If the token is valid, return the protected data
# If the token is invalid, raise an HTTPException with a 401 status code
# Here, we are assuming that the external OAuth2 server has a /introspect endpoint
# that can be used to verify the token
from requests import get
response = get("external-oauth2-server.com/introspect", headers={"Authorization": f"Bearer {token}"})
if response.status_code != 200:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
# If the token is valid, return the protected data
return {"data": "This is protected data"}
This example uses the OAuth2PasswordBearer class from FastAPI's built-in fastapi.security module to define an OAuth2 password bearer scheme. The Depends function is then used to dependency inject the token from the Authorization header into the protected_route endpoint.
The protected_route endpoint then verifies the token with the external OAuth2 server by sending a request to the server's /introspect endpoint. If the token is valid, the endpoint returns the protected data. If the token is invalid, the endpoint raises an HTTPException with a 401 status code.
Note that this is just an example and you will need to modify it to fit your specific use case. For example, you may need to send additional data in the request to the /introspect endpoint, or you may need to handle errors or edge cases differently.
I hope this helps! Let me know if you have any questions.