Files
aicheckv2/app/application/token_middleware.py
2025-02-19 11:47:33 +08:00

34 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import status
from starlette.middleware.base import BaseHTTPMiddleware
from urllib.request import Request
from jwt import PyJWTError
from app.common import reponse_code as rc
from app.common import jwt_check as jc
class TokenMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
async def dispatch(self, request: Request, call_next):
"""
验证token中间件
:param request: Request请求
:param call_next:
:return:
"""
token = request.headers.get('Authorization')
path = request.url.path
if '/login' in path:
response = await call_next(request)
return response
if not token:
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "缺少Token请重新验证")
try:
jc.check_token(token)
return await call_next(request)
except PyJWTError as error:
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "Token错误或失效请重新验证")