高级主题
扩展应用程序模型
应用程序实例表示 Client 在 Authorization server 。通常,在客户端开发人员登录到授权服务器并传递一些标识应用程序本身的数据(比如应用程序名称)之后,应用程序就会被发布给他们。Django OAuth工具包提供了应用程序模型的一个非常基本的实现,其中只包含所有OAuth过程中严格需要的数据,但您可能需要一些额外的信息,如应用程序徽标、对某些用户协议的接受等。
- class AbstractApplication(models.Model)
这是实现Django OAuth工具包工作的最低要求的基类
client_idThe client identifier issued to the client during the registration process as described in RFC6749 Section 2.2user参考Django用户redirect_uris允许的重定向URI列表。该字符串由用空格分隔的有效URL组成post_logout_redirect_urisRP启动注销后允许的重定向URI列表。该字符串由用空格分隔的有效URL组成allowed_origins为令牌终结点启用CORS的源URI列表。该字符串由用空格分隔的有效URL组成client_typeClient type as described in RFC6749 Section 2.1authorization_grant_type应用程序可用的授权流client_secretConfidential secret issued to the client during the registration process as described in RFC6749 Section 2.2name应用程序的友好名称
Django OAuth工具包允许您以类似于Django的定制用户模型的方式扩展AbstractApplication模型。
如果您需要应用程序徽标和用户协议接受字段,您可以在您的Django应用程序中执行此操作(前提是您的应用程序位于 INSTALLED_APPS 在您的设置模块中):
from django.db import models
from oauth2_provider.models import AbstractApplication
class MyApplication(AbstractApplication):
logo = models.ImageField()
agree = models.BooleanField()
然后,您需要告诉Django OAuth工具包您希望使用哪个模型来表示应用程序。在您的设置模块中写下如下内容::
OAUTH2_PROVIDER_APPLICATION_MODEL = 'your_app_name.MyApplication'
请注意,当您打算交换应用程序模型时,应在设置之前创建并运行定义交换的应用程序模型的迁移 OAUTH2_PROVIDER_APPLICATION_MODEL 。你会碰上 models.E022 在核心系统中检查您是否没有得到正确的订单。
您可以通过添加以下内容来强制迁移提供自定义模型以正确的顺序运行:
run_before = [
('oauth2_provider', '0001_initial'),
]
到迁移班。
仅此而已,现在Django OAuth工具包将在任何需要应用程序实例的地方使用您的模型。
备注
OAUTH2_PROVIDER_APPLICATION_MODEL 是唯一一个没有命名空间的设置变量,这是因为Django目前实现可交换模型的方式。看见 issue #90 了解更多细节。
多笔赠款
默认应用程序模型支持单一OAuth授权(例如授权码、客户端凭据)。如果需要应用程序支持多个授权,请重写 allows_grant_type 方法。例如,如果希望应用程序支持授权码 and 客户端凭据授予时,您可以执行以下操作:
from oauth2_provider.models import AbstractApplication
class MyApplication(AbstractApplication):
def allows_grant_type(self, *grant_types):
# Assume, for this example, that self.authorization_grant_type is set to self.GRANT_AUTHORIZATION_CODE
return bool( set([self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS]) & grant_types )
压倒一切的视图
您可能想要覆盖Django OAuth工具包中的整个视图,例如,如果您想要根据某些查询参数更改未注册用户的登录视图。
为此,您需要编写一个定制的urlPatterns
from django.urls import re_path
from oauth2_provider import views as oauth2_views
from oauth2_provider import urls
from .views import CustomeAuthorizationView
app_name = "oauth2_provider"
urlpatterns = [
# Base urls
re_path(r"^authorize/", CustomeAuthorizationView.as_view(), name="authorize"),
re_path(r"^token/$", oauth2_views.TokenView.as_view(), name="token"),
re_path(r"^revoke_token/$", oauth2_views.RevokeTokenView.as_view(), name="revoke-token"),
re_path(r"^introspect/$", oauth2_views.IntrospectTokenView.as_view(), name="introspect"),
] + urls.management_urlpatterns + urls.oidc_urlpatterns
然后您可以替换 oauth2_provider.urls 使用您的URL文件的路径,但确保您保留与以前相同的命名空间。
from django.urls import include, path
urlpatterns = [
...
path('o/', include('path.to.custom.urls', namespace='oauth2_provider')),
]
如果您不需要,此方法还允许删除一些URL(如管理)URL。