一个 Flask 装饰器,它为基于自编码 JWT 的承载访问令牌添加本地和远程 OAuth2 验证。
项目描述
这个 Python 包提供了一个Flask装饰器,它为基于自编码JWT ( RFC-7519 ) 的Bearer ( RFC-6750 ) 访问令牌添加本地和远程OAuth2 ( RFC-6749 ) 验证。
它仅涵盖资源服务器 (API)所需的验证逻辑,不提供 OAuth2 流的任何实现(例如授权代码流)。
要求
配置
最小配置期望OAUTH2_ISSUER
设置指向发行者的属性:
app.config['OAUTH2_ISSUER'] = 'https://<your-issuer>/oauth2'
这将在从授权服务器 ( RFC-7800 )下载公钥 ( RFC-7517 ) 后执行本地令牌验证。
如果您还需要执行远程令牌验证 ( RFC-7662 )OAUTH2_CLIENT_ID
并且OAUTH2_CLIENT_SECRET
需要配置:
app.config['OAUTH2_CLIENT_ID'] = 'your-client-id'
app.config['OAUTH2_CLIENT_SECRET'] = 'your-client-secret'
如果您的授权服务器使用轮换公钥,则OAUTH2_JWKS_UPDATE_INTERVAL
可以将(以秒为单位)配置为定期从授权服务器下载最新的公钥:
app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 3600
对于更严格的验证,建议配置一个OAUTH2_AUDIENCE
来验证令牌:
app.config['OAUTH2_AUDIENCE'] = 'api://default'
用法
要为您的端点提供 OAuth2 令牌验证,只需添加OAuth2Decorator
:
from flask_oauth2_validation import OAuth2Decorator
oauth2 = OAuth2Decorator(app)
@oauth2.requires_token()
@app.route('/protected')
def protected():
pass
这将仅执行本地令牌验证。要启用远程令牌验证,您需要提供introspect=True
参数:
@oauth2.requires_token(introspect=True)
@app.route('/protected')
def protected():
pass
如果您需要一个或多个范围来允许执行,请添加scopes=[...]
参数:
@oauth2.requires_token(scopes=['profile', 'email'])
@app.route('/protected')
def protected():
pass
要在您的方法中使用令牌,您可以通过以下OAuth2Decorator
对象访问它:
@oauth2.requires_token()
@app.route('/protected')
def protected():
token: dict = oauth2.token
pass
执照
MIT License
Copyright (c) 2021 Henrik Sachse
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.