支持多种身份验证类型的Falcon身份验证中间件。
项目描述
falcon-auth2
支持多种身份验证方案的Falcon身份验证中间件。
安装
$ pip install falcon-auth2[jwt]
上述命令将安装 falcon-auth2
及使用 JWT
身份验证后端所需的依赖项。
如果您计划使用ASGI运行异步falcon,请执行
$ pip install falcon-auth2[jwt, async]
用法
此包提供了一种使用所选身份验证后端对传入请求进行身份验证的falcon中间件。中间件允许排除一些路由或方法的身份验证。在身份验证成功后,中间件将请求中识别的用户添加到 请求上下文
中。当使用falcon v3+时,中间件也支持异步执行。
请参阅 readme_example 和 readme_example_async 以获取完整示例。
import falcon
from falcon_auth2 import AuthMiddleware
from falcon_auth2.backends import BasicAuthBackend
def user_loader(attributes, user, password):
if authenticate(user, password):
return {"username": user}
return None
auth_backend = BasicAuthBackend(user_loader)
auth_middleware = AuthMiddleware(auth_backend)
# use falcon.API in falcon 2
app = falcon.App(middleware=[auth_middleware])
class HelloResource:
def on_get(self, req, resp):
# req.context.auth is of the form:
#
# {
# 'backend': <instance of the backend that performed the authentication>,
# 'user': <user object retrieved from the user_loader callable>,
# '<backend specific item>': <some extra data that may be added by the backend>,
# ...
# }
user = req.context.auth["user"]
resp.media = {"message": f"Hello {user['username']}"}
app.add_route('/hello', HelloResource())
为资源覆盖身份验证
该中间件允许每个资源自定义用于认证或排除的方法的后端。资源还可以指定不需要认证。
from falcon_auth2 import HeaderGetter
from falcon_auth2.backends import GenericAuthBackend
def user_header_loader(attr, user_header):
# authenticate the user with the user_header
return user_header
class GenericResource:
auth = {
"backend": GenericAuthBackend(user_header_loader, getter=HeaderGetter("User")),
"exempt_methods": ["GET"],
}
def on_get(self, req, resp):
resp.media = {"type": "No authentication for GET"}
def on_post(self, req, resp):
resp.media = {"info": f"User header {req.context.auth['user']}"}
app.add_route("/generic", GenericResource())
class NoAuthResource:
auth = {"auth_disabled": True}
def on_get(self, req, resp):
resp.text = "No auth in this resource"
def on_post(self, req, resp):
resp.text = "No auth in this resource"
app.add_route("/no-auth", NoAuthResource())
支持的认证后端
BasicAuthBackend
实现了HTTP基本认证,客户端应通过在HTTP头中的Authorization
字段以base64
编码的格式传递凭证(用户名:密码)来进行认证。
JWTAuthBackend
实现了JSON Web Token (JWT)标准,客户端应通过在Authorization
HTTP头中传递令牌密钥来进行认证。此后端使用了Authlib库。
GenericAuthBackend
是一种通用的认证后端,将请求中认证信息的验证委托给user_loader
可调用对象。此后端可用于快速实现自定义认证方案,或作为其他认证库的适配器。
NoAuthBackend
不执行任何认证检查的后端,当与MultiAuthBackend
结合使用时,可用于为未认证用户提供后备。
元认证后端
CallBackBackend
在另一个后端成功或失败进行认证时通知。此后端将所有认证操作委托给提供的backend
。
MultiAuthBackend
用于组合多个认证后端的后端。如果提供的任一后端可以认证请求,则此后端成功认证请求。
关于Falcon
Falcon是用于在Python中构建可靠、正确和高性能REST API、微服务、代理和应用后端的简约Web API框架。
感谢
此包受到了falcon-auth和falcon-authentication包的启发。
许可证
falcon-auth2
在Apache-2.0许可证下分发。
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。