I am developing a Flutter app that uses Auth0 for authentication. I have created a Native app in Auth0. After successful authentication, the Flutter app obtains a token from Auth0. I now need to verify this token on my FastAPI backend.
How can I check if this token is valid and correctly issued by Auth0? I’m not sure how to implement this part of the process. Can someone guide me through the steps or share any examples?
Any help would be greatly appreciated!
Here’s my code
from typing import Optional
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import SecurityScopes, HTTPAuthorizationCredentials, HTTPBearer
class UnauthorizedException(HTTPException):
def __init__(self, detail: str, **kwargs):
super().__init__(status.HTTP_403_FORBIDDEN, detail=detail)
class UnauthenticatedException(HTTPException):
def __init__(self):
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Requires authentication"
)
class VerifyToken:
"""Does all the token verification using PyJWT"""
def __init__(self):
self.auth0_domain = 'dev-5c7****.com'
self.auth0_algorithms = 'RS256'
self.auth0_api_audience = '' #The problem is that auth0's native app doesn't have this
self.auth0_issuer = f'https://{self.auth0_domain}/'
jwks_url = f'https://{self.auth0_domain}/.well-known/jwks.json'
self.jwks_client = jwt.PyJWKClient(jwks_url)
async def verify(self,
security_scopes: SecurityScopes,
token: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer())
):
if token is None:
raise UnauthenticatedException
try:
signing_key = self.jwks_client.get_signing_key_from_jwt(
token.credentials
).key
except jwt.exceptions.PyJWKClientError as error:
raise UnauthorizedException(str(error))
except jwt.exceptions.DecodeError as error:
raise UnauthorizedException(str(error))
except Exception as error:
raise UnauthorizedException(str(error))
try:
payload = jwt.decode(
token.credentials,
signing_key,
algorithms=self.auth0_algorithms,
audience=self.auth0_api_audience,
issuer=self.auth0_issuer,
)
except Exception as error:
raise UnauthorizedException(str(error))
return payload
1
I found the issue. The Auth0 Dashboard does not allow native apps to set the audience, but it can actually be specified in the SDK. If the token you get after logging in with the native app cannot be decoded, it’s because you haven’t specified the audience. Once specified, the token can be decoded.