tomasvotava/fastapi-sso

How can we integrate JWT token mechanism with generic SSO?

Closed this issue · 1 comments

How can we integrate JWT token mechanism with generic SSO?

This is a question not exactly related to fastapi-sso, but let me at least point you in the correct direction.

JWTs are JSON objects signed with a secret key that can be verified using the secret key. This means you can trust the contents of the JSON even if it comes from the user as they wouldn't be able to sign it without the secret key. Thanks to this you can make the user (or the frontend of your application) send you the JWT instead of a session id (which is the way it was done before that) and use the data in the JSON object instead of looking the data up in the database based on the session.

Once you verify the user with fastapi-sso, you can generate such JWT and return it to the user as a cookie. You can then read the cookie in every request, verify the signature and use the data in the JWT.

I will omit some of code in the example (I am using python-jose)

from jose import jwt
from jose.exceptions import JWTError
from fastapi import Cookie, HTTPException
from fastapi.responses import JSONResponse

MY_SECRET_KEY = "supersecret"
...

@app.get("/google/callback")
async def google_callback(request: Request):
    """Process login response from Google and return user info"""
    user = await google_sso.verify_and_process(request)
    token = jwt.encode(user.dict(), MY_SECRET_KEY, algorithm="HS256")
    response = JSONResponse(content={"token": token})
    response.set_cookie(key="token", value=token)
    return response

@app.get("/protected-endpoint")
async def protected_endpoint(token: Optional[str] = Cookie(default=None)):
    if not token:
       raise HTTPException(status=401, detail="Not authorized")
    try:
       jwt.decode(token, MY_SECRET_KEY, algorithms=["HS256"])
    except JWTError:
        raise HTTPException(status=401, detail="Provided token is invalid or expired")
    return {"message": "You got all the way here, you are logged in!"}