middlewares.py 834 B

1234567891011121314151617181920212223242526
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from starlette.authentication import AuthenticationBackend, SimpleUser, AuthCredentials
  4. from db.asyncredis import redis_client
  5. from utils.depends import check_access_token
  6. class JwtAuth(AuthenticationBackend):
  7. async def authenticate(self, conn):
  8. if "Authorization" not in conn.headers:
  9. return None
  10. token = conn.headers["Authorization"].split(" ")[-1]
  11. token_payload = check_access_token(token)
  12. # 检验token是否过期?
  13. token_key = "{}:{}:access-token".format(
  14. token_payload.sub.get("school", None), token_payload.sub["sub"])
  15. access_token = redis_client.get(token_key)
  16. if not access_token:
  17. return None
  18. return AuthCredentials(["authenticated"]), SimpleUser(token_payload.sub)