隐藏页面特效

FastAPI系列:自定义认证

from typing import Optional, Tuple from fastapi import FastAPI, Request from pydantic import BaseModel # 通过starlette.authentication导入AuthenticationBackend from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser, requires from starlette.middleware import Middleware from starlette.middleware.authentication import AuthenticationMiddleware from starlette.requests import HTTPConnection class UserReq(BaseModel): username: str password: str class UsernameAuthBackend(AuthenticationBackend): keyword = 'bearer' def __init__(self, username): self.username = username # 必须实现该方法,而且必须async修饰 async def authenticate(self, request): """源码 async def authenticate( self, conn: HTTPConnection # 传入HTTP连接的基类,用于提供 Request 和 WebSocket 通用的任何功能。 ) -> typing.Optional[typing.Tuple["AuthCredentials", "BaseUser"]]: raise NotImplementedError() # pragma: no cover """ if "Authorization" not in request.headers: return auth = request.headers["Authorization"] print(auth) try: scheme, username = auth.split() if scheme.lower().strip() != self.keyword.strip(): return except: raise AuthenticationError('Invalid basic auth credentials') if not username == self.username: return # authenticate方法必须返回AuthCredentials和BaseUser,AuthCredentials必须是用列表嵌套字符串的形式, return AuthCredentials(["authenticated"]), SimpleUser(username) middleware = [Middleware(AuthenticationMiddleware, backend=UsernameAuthBackend("liuwei"))] app = FastAPI(middleware=middleware) @requires("authenticated") @app.get("/login") def login(user: UserReq, request: Request): return user

__EOF__

本文作者404 Not Found
本文链接https://www.cnblogs.com/weiweivip666/p/18041433.html
关于博主:可能又在睡觉
版权声明:转载请注明出处
声援博主:如果看到我睡觉请喊我去学习
posted @   我在路上回头看  阅读(255)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2022-02-28 方法指针或非指针类型接收器
点击右上角即可分享
微信分享提示