Created
June 25, 2024 13:51
-
-
Save GGontijo/42553836ff313307e56b7c3d8edb61ce to your computer and use it in GitHub Desktop.
validate jwt fields from microsoft entra id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import jwt | |
from fastapi import Depends, HTTPException, Response, status | |
from fastapi.security import OAuth2PasswordBearer | |
from helpers.config_helper import Config | |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") | |
class OAuth2TokenValidation: | |
def __init__(self): | |
_config_loader = Config() | |
_config = _config_loader.get("azure_service") | |
self.tenant_id = _config['tenant_id'] | |
self.client_id = _config['client_id'] | |
self.authority = f"https://login.microsoftonline.com/{self.tenant_id}" | |
def validate_token(self, token: str = Depends(oauth2_scheme)): | |
""" | |
Decodes the token and validates its fields without signature validation. | |
:param token: The JWT token to validate | |
:return: The decoded token payload if valid, else raises an exception | |
""" | |
try: | |
payload = jwt.decode(token, options={"verify_signature": False}) | |
if payload.get('iss') != f"https://sts.windows.net/{self.tenant_id}/": | |
raise PermissionError("Invalid issuer") | |
if payload.get('appid') != self.client_id: | |
raise PermissionError("Invalid appid") | |
if time.time() > payload.get('exp', 0): | |
raise PermissionError("Token has expired") | |
return payload | |
except jwt.DecodeError: | |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") | |
except PermissionError as e: | |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e)) | |
except Exception as e: | |
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment