Authentication Backends

Note

基于令牌的身份验证和JWT身份验证可以同时共存. 只需按照两种身份验证方法的说明进行操作即可.

Token Based Authentication

Add 'rest_framework.authtoken' to INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.auth',
    (...),
    'rest_framework',
    'rest_framework.authtoken',
    'djoser',
    (...),
]

配置urls.py 注意djoser.url.authtoken模块路径:

urlpatterns = [
    (...),
    url(r'^auth/', include('djoser.urls')),
    url(r'^auth/', include('djoser.urls.authtoken')),
]

rest_framework.authentication.TokenAuthentication添加到Django REST Framework身份验证策略元组中:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        (...)
    ),
}

运行迁移-此步骤将为authauthtoken应用程序创建表:

$ ./manage.py migrate

JSON Web Token Authentication

Django Settings

rest_framework_simplejwt.authentication.JWTAuthentication添加到Django REST Framework身份验证策略元组中:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        (...)
    ),
}

配置django-rest-framework-simplejwt以使用Authorization:JWT <access_token>标头:

SIMPLE_JWT = {
   'AUTH_HEADER_TYPES': ('JWT',),
}

urls.py

使用djoser.url.jwt模块路径配置urls.py

urlpatterns = [
    (...),
    url(r'^auth/', include('djoser.urls')),
    url(r'^auth/', include('djoser.urls.jwt')),
]