隐藏页面特效

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 @   我在路上回头看  阅读(252)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-02-28 方法指针或非指针类型接收器
点击右上角即可分享
微信分享提示