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',
}