jose_utils.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import arrow
  2. from jwcrypto import jwk, jwt
  3. from app.config import OPENID_PRIVATE_KEY_PATH, URL
  4. from app.log import LOG
  5. from app.models import ClientUser
  6. with open(OPENID_PRIVATE_KEY_PATH, "rb") as f:
  7. key = jwk.JWK.from_pem(f.read())
  8. def get_jwk_key() -> dict:
  9. return key._public_params()
  10. def make_id_token(client_user: ClientUser):
  11. """Make id_token for OpenID Connect
  12. According to RFC 7519, these claims are mandatory:
  13. - iss
  14. - sub
  15. - aud
  16. - exp
  17. - iat
  18. """
  19. claims = {
  20. "iss": URL,
  21. "sub": str(client_user.id),
  22. "aud": client_user.client.oauth_client_id,
  23. "exp": arrow.now().shift(hours=1).timestamp,
  24. "iat": arrow.now().timestamp,
  25. }
  26. claims = {**claims, **client_user.get_user_info()}
  27. jwt_token = jwt.JWT(header={"alg": "RS256", "kid": "simple-login"}, claims=claims)
  28. jwt_token.make_signed_token(key)
  29. return jwt_token.serialize()
  30. def verify_id_token(id_token) -> bool:
  31. try:
  32. jwt.JWT(key=key, jwt=id_token)
  33. except Exception:
  34. LOG.exception("id token not verified")
  35. return False
  36. else:
  37. return True