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

时间:2021-01-21 16:23:43

标签: python flask oauth-2.0 authlib

Authlib 文档描述了资源服务器如何从实现 BearerTokenValidator 的客户端验证 auth_token:

    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

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

就我而言,我无权访问令牌数据库,并且 AS 仅提供一个 REST 自省端点来验证令牌是否有效。

我打算使用 requests 库并将令牌传递给 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()

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

1 个答案:

答案 0 :(得分:1)

根据 Authlib 文档,有一种内置方法可以解决此问题。感谢@lepture 在评论中指出这一点。

我们可以扩展一个内置的 IntrospectTokenValidator 来实现我们的验证器。

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