| 1 |
# Ref: https://github.com/fastapi/fastapi/issues/14454 |
| 2 |
|
| 3 |
from typing import Annotated |
| 4 |
|
| 5 |
from fastapi import Depends, FastAPI, Security |
| 6 |
from fastapi.security import OAuth2AuthorizationCodeBearer |
| 7 |
from fastapi.testclient import TestClient |
| 8 |
from inline_snapshot import snapshot |
| 9 |
|
| 10 |
oauth2_scheme = OAuth2AuthorizationCodeBearer( |
| 11 |
authorizationUrl="api/oauth/authorize", |
| 12 |
tokenUrl="/api/oauth/token", |
| 13 |
scopes={"read": "Read access", "write": "Write access"}, |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
async def get_token(token: Annotated[str, Depends(oauth2_scheme)]) -> str: |
| 18 |
return token |
| 19 |
|
| 20 |
|
| 21 |
app = FastAPI(dependencies=[Depends(get_token)]) |
| 22 |
|
| 23 |
|
| 24 |
@app.get("/admin", dependencies=[Security(get_token, scopes=["read", "write"])]) |
| 25 |
async def read_admin(): |
| 26 |
return {"message": "Admin Access"} |
| 27 |
|
| 28 |
|
| 29 |
client = TestClient(app) |
| 30 |
|
| 31 |
|
| 32 |
def test_read_admin(): |
| 33 |
response = client.get("/admin", headers={"Authorization": "Bearer faketoken"}) |
| 34 |
assert response.status_code == 200, response.text |
| 35 |
assert response.json() == {"message": "Admin Access"} |
| 36 |
|
| 37 |
|
| 38 |
def test_openapi_schema(): |
| 39 |
response = client.get("/openapi.json") |
| 40 |
assert response.status_code == 200, response.text |
| 41 |
assert response.json() == snapshot( |
| 42 |
{ |
| 43 |
"openapi": "3.1.0", |
| 44 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 45 |
"paths": { |
| 46 |
"/admin": { |
| 47 |
"get": { |
| 48 |
"summary": "Read Admin", |
| 49 |
"operationId": "read_admin_admin_get", |
| 50 |
"responses": { |
| 51 |
"200": { |
| 52 |
"description": "Successful Response", |
| 53 |
"content": {"application/json": {"schema": {}}}, |
| 54 |
} |
| 55 |
}, |
| 56 |
"security": [ |
| 57 |
{"OAuth2AuthorizationCodeBearer": ["read", "write"]} |
| 58 |
], |
| 59 |
} |
| 60 |
} |
| 61 |
}, |
| 62 |
"components": { |
| 63 |
"securitySchemes": { |
| 64 |
"OAuth2AuthorizationCodeBearer": { |
| 65 |
"type": "oauth2", |
| 66 |
"flows": { |
| 67 |
"authorizationCode": { |
| 68 |
"scopes": { |
| 69 |
"read": "Read access", |
| 70 |
"write": "Write access", |
| 71 |
}, |
| 72 |
"authorizationUrl": "api/oauth/authorize", |
| 73 |
"tokenUrl": "/api/oauth/token", |
| 74 |
} |
| 75 |
}, |
| 76 |
} |
| 77 |
} |
| 78 |
}, |
| 79 |
} |
| 80 |
) |