I use FastAPI and Auth0 to restrict access to specific endpoints for specific users. In the Auth0 dashboard, I have defined various user roles and assigned them to individual users. As a result, each user possesses a role.
Currently, my objective is to retrieve the user's roles. I added this code to Auth pipline > Rules to get user roles in token:
function (user, context, callback) {
var namespace = 'https://domain.auth0.com/';
context.idToken[namespace] = user.roles;
return callback(null, user, context);
}
This is my FastAPI code that should retrieve the user token. (I am not sure whether to get user roles here or not).
from dataclasses import dataclass
import jwt
from config import settings
from custom_exceptions import BadCredentialsException, UnableCredentialsException
@dataclass
class JsonWebToken:
"""Perform JSON Web Token (JWT) validation using PyJWT"""
jwt_access_token: str
auth0_issuer_url: str = f"https://{settings.auth0_domain}/"
auth0_audience: str = settings.auth0_audience
algorithm: str = "RS256"
jwks_uri: str = f"{auth0_issuer_url}.well-known/jwks.json"
def validate(self):
try:
jwks_client = jwt.PyJWKClient(self.jwks_uri)
jwt_signing_key = jwks_client.get_signing_key_from_jwt(
self.jwt_access_token
).key
payload = jwt.decode(
self.jwt_access_token,
jwt_signing_key,
algorithms=self.algorithm,
audience=self.auth0_audience,
issuer=self.auth0_issuer_url,
)
except jwt.exceptions.PyJWKClientError:
raise UnableCredentialsException
except jwt.exceptions.InvalidTokenError:
raise BadCredentialsException
return payload
When I print `payload`:
{
'iss': 'https://domain.auth0.com/',
'sub': 'kjn8DLZ6TNJ!9ube$rvE@clients',
'aud': 'https://domain.auth0.com/api/v2/',
'iat': 1694021374,
'exp': 1696613374,
'azp': 'kjn8DLZ6TNJ!9ube$rvE',
'gty': 'client-credentials'
}