跳转到主要内容

Quart扩展,提供安全的cookie身份验证

项目描述

Build Status docs pypi python license

Quart-Auth是为Quart提供的扩展,用于提供安全的cookie身份验证(会话管理)。它允许进行登录、身份验证和注销会话。

用法

要使用Quart-Auth与Quart应用程序,您必须创建一个QuartAuth并使用应用程序初始化它,

app = Quart(__name__)
QuartAuth(app)

或者通过工厂模式,

auth_manager = QuartAuth()

def create_app():
    app = Quart(__name__)
    auth_manager.init_app(app)
    return app

此外,您还需要配置Quart-Auth,默认为最安全。至少您需要设置密钥,

app.secret_key = "secret key"  # Do not use this key

您可以通过以下方式生成密钥,

>>> import secrets
>>> secrets.token_urlsafe(16)

您还可能需要禁用安全cookie以在开发中使用,请参见下面的配置。

初始化QuartAuth后,您可以使用login_required函数来装饰只能由已认证用户访问的路由,

from quart_auth import login_required

@app.route("/")
@login_required
async def restricted_route():
    ...

如果没有用户登录,将引发Unauthorized异常。要捕获它,请安装错误处理器,

@app.errorhandler(Unauthorized)
async def redirect_to_login(*_: Exception) -> ResponseReturnValue:
    return redirect(url_for("login"))

您还可以使用login_userlogout_user函数来为特定的AuthenticatedUser实例开始和结束会话。

from quart_auth import AuthUser, login_user, logout_user

@app.route("/login")
async def login():
    # Check Credentials here, e.g. username & password.
    ...
    # We'll assume the user has an identifying ID equal to 2
    login_user(AuthUser(2))
    ...

@app.route("/logout")
async def logout():
    logout_user()
    ...

用户(无论是否认证)都可通过全局 current_user 获取,包括在模板中。

from quart import render_template_string
from quart_auth import current_user

@app.route("/")
async def user():
    return await render_template_string("{{ current_user.is_authenticated }}")

贡献

Quart-Auth 是在 GitHub 上开发的。您非常欢迎提交 问题 或提出 pull请求

测试

使用 Tox 是测试 Quart-Auth 的最佳方式,

$ pip install tox
$ tox

这将检查代码风格并运行测试。

帮助

Quart-Auth 的 文档 是开始的地方,之后可以在 Stack Overflow 中搜索或 在 Gitter 上寻求帮助。如果您仍然找不到答案,请 打开一个问题

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

quart_auth-0.10.1.tar.gz (9.3 kB 查看哈希值)

上传时间

构建分发

quart_auth-0.10.1-py3-none-any.whl (9.6 kB 查看哈希值)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面