drf验证

drf验证:

    1、在settings中配置:

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

    2、在settings中的APPS中配置:

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

    3、在urls中配置:    

urlpatterns += [ url(r'^api-token-auth/', CustomAuthToken.as_view())
]

有局限性 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

JWT验证:

1、pip install djangorestframework-jwt
2、settings中:
    REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}
3、urls.py中:
    from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

api-token-auth可以自定义的
4、可以自定义用户验证:以用户登陆为例:
  1)将3中的url改为:url(r'^login/', obtain_jwt_token),
  2) 在settings中设置一个变量:
      AUTHENTICATION_BACKENDS = ('users.viewsCustomBackend',)
  3) 然后我们就可以在users中定义一个类:
      把models中的 from django.contrib.auth import get_user_model
                   User = get_user_model()
      拿到users/views.py中,然后加上:
          from django.contrib.auth.backends import ModelBackend
          from django.db.models import Q
          class CustomBackend(ModelBackend):
              """
              自定义用户验证,要继承这个ModelBackend,重写authenticate这个函数
              """
              def authenticate(self, username=None,password=None,**wargs):
                 try:
                      user = User.objects.get(Q(username=username)|Q(mobile=username))
                      if user.check_password(password):
                          return user
                 except Exception as e:
                      return None

----------------------------------------------------------------------------------------------
这个JWT是可以设置过期时间的:
  1) 在settings中:
      import datetime
      JWT_AUTH = {
           'JWT_EXPIRATION_DELTA':datetime.timedelta(day=7),
           'JWT_AUTH_HEADER_PRFIX':'JWT',
      }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值