Skip to content

Instantly share code, notes, and snippets.

@lwzm
Created January 20, 2022 09:20
Show Gist options
  • Save lwzm/6b2f4d61f071ac4daf3252238b45581e to your computer and use it in GitHub Desktop.
Save lwzm/6b2f4d61f071ac4daf3252238b45581e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from requests import Session
from furl import furl
app = FastAPI()
url_openid = "https://auth.i8c.cc/auth/realms/x/.well-known/openid-configuration"
client_id = "q"
http = Session()
cfg = http.get(url_openid).json()
tmp = {}
@app.get("/")
async def test(req: Request, code: str = "", state: str = ""):
if not code:
f = furl(cfg["authorization_endpoint"])
state = str(uuid4())
tmp[state] = str(req.url)
f.args.update(
{
"client_id": client_id,
"response_type": "code",
"state": state,
"redirect_uri": tmp[state],
}
)
return RedirectResponse(f.url)
t = http.post(
cfg["token_endpoint"],
data={
"client_id": client_id,
"redirect_uri": tmp.pop(state),
"grant_type": "authorization_code",
"code": code,
},
).json()
authorization = t["token_type"] + " " + t["access_token"]
rsp = http.get(cfg["userinfo_endpoint"], headers={"Authorization": authorization})
return rsp.json()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", forwarded_allow_ips="*")
# equivalent to:
# $ uvicorn --forwarded-allow-ips '*' --host 0.0.0.0 asgi:app
# $ FORWARDED_ALLOW_IPS='*' uvicorn --host 0.0.0.0 asgi:app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment