我正在开发一个使用 Auth0 进行身份验证的 Flutter 应用程序。我在 Auth0 中创建了一个本机应用程序。认证成功后,Flutter应用会从Auth0获取token。我现在需要在我的 FastAPI 后端验证此令牌。
如何检查此令牌是否有效且由 Auth0 正确颁发?我不确定如何实现这部分过程。有人可以指导我完成这些步骤或分享任何示例吗?
任何帮助将不胜感激!
这是我的代码
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
我发现了问题。 Auth0 Dashboard 不允许本机应用程序设置受众,但实际上可以在 SDK 中指定。如果您使用原生应用登录后获得的token无法被解码,那是因为您没有指定受众。一旦指定,令牌就可以被解码。