自定义授予类型

编写自定义授权类型对于实现早期草案中的规范很有用,或者实现由特定OAuth2.0授权服务器文档提供但不由oauthlib提供的授权。作为参考,任何具有明确规范的授权类型都可以集成到oauthlib中,只需为其创建一个公关!看见 how to contribute here

请了解如何创建新授权并在终结点中使用它:

1.定义您的授权类型

代码的核心是通过子类化完成的 GrantTypeBase 。如果要在授权端点中使用它,则必须实现 create_authorization_response() ,如果要使用令牌端点,请实现 create_token_response() 。您也可以同时实现这两种方法。

2.落实拨款

在该方法的实现中,您必须:

  • 添加请求的验证(语法、参数...)

  • 调用和编排一个或多个请求验证器调用

  • 生成并返回HTTP响应

如果需要,您可以定义新的请求验证器方法,或者重用现有的方法。

3.将其与端点关联

然后,一旦实现,您必须实例化授权对象并将其绑定到您的端点。要么 AuthorizationEndpointTokenEndpoint 或者两者都有。

4.示例

此示例演示如何将简单的扩展添加到 Token endpoint

  • 创建一个新类 MyCustomGrant ,并实施 create_token_response

  • 执行基本和定制请求验证,然后调用 Request Validator 来扩展实现者的接口。

  • 实例化新授权,并将其与现有的 Server

grant_name = 'urn:ietf:params:oauth:grant-type:my-custom-grant'

class MyCustomGrant(GrantTypeBase):
    def create_token_response(self, request, token_handler):
        if not request.grant_type == grant_name:
            raise errors.UnsupportedGrantTypeError(request=request)

        # implement your custom validation checks
        # ..
        self.request_validator.your_custom_check(request)

        token = token_handler.create_token(request)
        return self._get_default_headers(), json.dumps(token), 200

def setup_oauthlib():
    my_custom_grant = MyCustomGrant()
    server = Server(request_validator)
    server.grant_types[grant_name] = my_custom_grant

您可以直接在现有授权和现有服务器的代码源中找到具体的示例。请参阅中的授予类型 oauthlib.oauth2.rfc749.grant_types 和中的服务器 oauthlib.oauth2.rfc749.endpoints.pre_configured