美文网首页
tokenAuth 认证模式

tokenAuth 认证模式

作者: 爱修仙的道友 | 来源:发表于2019-04-25 14:30 被阅读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
  • You'll also need to create tokens for your users.
from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print(token.key)
  • 前端设置
# 加到请求头中
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
  • 前端插件测试


    image.png
    image.png
  • 前端使用方式

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
image.png
image.png
  • 存在问题:
    • 如果是分布式系统或者两套系统想用同一套认证系统,token只会保存到单一一台服务器当中,需要同步用户,
    • 过期时间
  • 全局配置副作用
    • 对于开放接口,即使访问失败,但也需要返回信息


      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

相关文章

网友评论

      本文标题:tokenAuth 认证模式

      本文链接:https://www.haomeiwen.com/subject/ckoiwqtx.html