使用远程身份验证服务器的Authlib令牌验证程序

2024-10-01 02:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

Authlib文档描述了资源服务器如何从实现BealerTokenValidator的客户端验证auth_令牌,如下所示:

    class MyBearerTokenValidator(BearerTokenValidator):
        def authenticate_token(self, token_string):
            return Token.query.filter_by(access_token=token_string).first()

    require_oauth = ResourceProtector()
    require_oauth.register_token_validator(MyBearerTokenValidator())

    # protecting the resource
    @app.route('/user')
    @require_oauth()
    def user_profile():
        user = current_token.user
        return jsonify(user)

https://docs.authlib.org/en/stable/flask/2/resource-server.html

此解决方案假定资源服务器可以访问身份验证服务器(AS)管理令牌的数据库,使用类似SQLAlchemy的ORM工具

在我的例子中,我没有访问令牌数据库的权限,AS只提供一个REST内省端点来验证令牌是否有效

我计划使用请求库并将令牌传递给AS以实现我的令牌验证器

class MyBearerTokenValidator(BearerTokenValidator):
    def authenticate_token(self, token_string):
    resp = requests.post("https://oauth-server-host/oauth/v2/introspection", auth=(id, secret), data={"token": "TK"})
    return resp.json()

这是正确的方法还是有更好、更标准的方法


Tags: 服务器tokenauthstringreturndefasrequire
1条回答
网友
1楼 · 发布于 2024-10-01 02:20:30

根据Authlib文档,有一种内置的方法来解决这个问题。谢谢你在评论中指出这一点

我们可以扩展一个内置的内省令牌验证器来实现我们的验证器

from authlib.oauth2.rfc7662 import IntrospectTokenValidator
from your_project import secrets

class MyIntrospectTokenValidator(IntrospectTokenValidator):
    def introspect_token(self, token_string):
        url = 'https://example.com/oauth/introspect'
        data = {'token': token_string, 'token_type_hint': 'access_token'}
        auth = (secrets.internal_client_id, secrets.internal_client_secret)
        resp = requests.post(url, data=data, auth=auth)
        return resp.json()

然后,我们可以将此令牌验证器注册到资源保护器:

require_oauth = ResourceProtector()
require_oauth.register_token_validator(MyIntrospectTokenValidator())

来源https://docs.authlib.org/en/latest/specs/rfc7662.html#use-introspection-in-resource-server

相关问题 更多 >