tokenAuth 认证模式

2019-04-25  本文已影响0人  爱修仙的道友

一、drf tokenAuth 认证模式
https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)
from rest_framework.authtoken import views
urlpatterns += [
    url(r'^api-token-auth/', views.obtain_auth_token)
]
makemigrations
migrate
image.png
from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print(token.key)
# 加到请求头中
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
image.png
image.png
  1. 取消全局配置,将配置单独放入视图中
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication',
    )
}
  1. 视图
from rest_framework.authentication import TokenAuthentication

class GoodsList(viewsets.ModelViewSet):
    # 单独配置(需要认证的接口)
    authentication_classes = (TokenAuthentication,)
image.png
  1. 不配置情况


    image.png
上一篇 下一篇

猜你喜欢

热点阅读