|
| 1 | +import urllib.parse |
| 2 | + |
| 3 | +from fastapi import APIRouter |
| 4 | +from fastapi import FastAPI |
| 5 | +from fastapi import Request |
| 6 | +from oauthlib.oauth2 import Server |
| 7 | +from starlette.responses import RedirectResponse |
| 8 | +from starlette.responses import Response |
| 9 | + |
| 10 | +from .backend import TestOAuth2 |
| 11 | +from .validator import TestValidator |
| 12 | + |
| 13 | + |
| 14 | +def get_idp(): |
| 15 | + application = FastAPI() |
| 16 | + app_router = APIRouter() |
| 17 | + oauth2_server = Server(TestValidator()) |
| 18 | + |
| 19 | + @app_router.get("/oauth/authorization") |
| 20 | + async def authorization(request: Request): |
| 21 | + uri = str(request.url) |
| 22 | + http_method = request.method |
| 23 | + headers = dict(request.headers) |
| 24 | + body_bytes = await request.body() |
| 25 | + body = body_bytes.decode("utf-8") |
| 26 | + |
| 27 | + scopes, credentials = oauth2_server.validate_authorization_request(uri, http_method, body, headers) |
| 28 | + uri = "http://idp/oauth/authorization?" + urllib.parse.urlencode({"scopes": ','.join(scopes), **credentials}) |
| 29 | + headers, body, status_code = oauth2_server.create_authorization_response(uri, http_method, body, headers) |
| 30 | + |
| 31 | + if status_code == 302: |
| 32 | + location = headers.get('Location', '') |
| 33 | + return RedirectResponse(location, headers=headers, status_code=status_code) |
| 34 | + |
| 35 | + return Response(content=body, status_code=status_code) |
| 36 | + |
| 37 | + @app_router.post("/oauth/token") |
| 38 | + async def token(request: Request): |
| 39 | + uri = str(request.url) |
| 40 | + http_method = request.method |
| 41 | + headers = dict(request.headers) |
| 42 | + body_bytes = await request.body() |
| 43 | + body = body_bytes.decode("utf-8") |
| 44 | + |
| 45 | + headers, body, status_code = oauth2_server.create_token_response(uri, http_method, body, headers, {}) |
| 46 | + |
| 47 | + return Response(content=body, headers=headers, status_code=status_code) |
| 48 | + |
| 49 | + application.include_router(app_router) |
| 50 | + return application |
0 commit comments