rest_framework-自带token认证

drf-token认证

  • settings配置全局认证

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            # Basic认证
            'rest_framework.authentication.BasicAuthentication',
            # Session认证
            'rest_framework.authentication.SessionAuthentication',
            # Token认证 一般不会配置全局的, 因为有些公开的数据是没token也可以访问的
            'rest_framework.authentication.TokenAuthentication',
        ]
    }
    
  • 局部只需要在你需要认证的视图里加认证类

    from rest_framework import mixins
    from rest_framework import viewsets
    # 导入drf自带的认证类
    from rest_framework.authentication import TokenAuthentication
    
    class UserProfileViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
      	# 指定queryset
        queryset = UserProfile.objects.all()
    
        # 指定序列化类
        serializer_class = UserSerializer
        
        # 指定认证类
        authentication_classes = [TokenAuthentication, ]
    
  • 注册rest_framework.authtoken

    INSTALLED_APPS = [
        ...
        'rest_framework.authtoken'
    ]
    
  • 实施迁移

    python manage.py makemigrations
    python manage.py migrate
    
  • 设置token验证url

    from rest_framework.authtoken import views
    urlpatterns = [
        url(r'^api-token-auth/', views.obtain_auth_token)
    ]
    
  • 当你用用户等入时, 没有token会帮你创建token, 有token会获取token, 但是这种没有过期时间, 用在分布式系统上也会出问题, 一般用jsonwebtoken

你可能感兴趣的:(#,rest_framework)