在终端中进入当前项目的虚拟环境,键入
pip install djangorestframework-jwt
pip install jwt
下载jwt。
每个用户在访问一些只有自己才能访问到的界面时,我们需要给一个凭证让这个用户的访问能够找到数据库中他自己的数据,但是这个凭证如果不加密,用户安全就得不到保障,这就是jwt的作用了。
jwt官方文档
因为django有默认的验证方法,所以我们可以直接在django的验证方法基础上加上jwt验证
在一个可以寻找到路径的文件夹中创建一个utils.py用来重写我的Authenticate,我选择直接在user模块中添加
from django.contrib.auth.backends import ModelBackend
import re
from . import constants
from . import models
from django.contrib.auth.hashers import check_password
ModelBackend中包含了我们需要重写的Authentication方法,然后check_password方法是用来加密密码的,我这里set_password和check_password方法出了一些小问题,就不使用了,不过如果可以还是加上密码的加密
class UserPhoneEmailAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
if re.match(constants.string_test_phonenum,username):
user=models.User.objects.get(phone=username)
用手机号码登录
elif re.match(constants.string_test_email,username):
user=models.User.objects.get(email=username)
用邮箱登录
else:
user=models.User.objects.get(username=username)
用户名登录
except models.User.DoesNotExist:
user =None
没有用户则返回一个匿名用户
if user is not None and password==user.password:
return user
如果用户名密码验证都通过返回该用户
在setting中添加以下字段
INSTALLED_APPS = [
........
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
}
import datetime
JWT_AUTH={
'JWT_EXPIRATION_DELTA':datetime.timedelta(days=1),
过期时间为一天
'JWT_RESPONSE_PAYLOAD_HANDLER':'user.utils.jwt_response_username_userid_token'
}
AUTHENTICATION_BACKENDS=[
'user.utils.UserPhoneEmailAuthBackend',
'django.contrib.auth.backends.ModelBackend'
]
并在user.utils中添加以下字段
def jwt_response_username_userid_token(token,user=None,request=None):
data={
'token':token,
'username':user.username,
'user_id':user.id
}
return data
设置完成
开启前面注释的jwt代码并在serializer中添加
from rest_framework_jwt.settings import api_settings
在field中添加
fields=(......,'token')
新注册带token的用户不能和之前用户同一手机号,所以最好用一个新手机或者把手机号码验证关掉。
注册时生成token,token保存在浏览器内存localstorage中