drf tooken
2023-06-03 本文已影响0人
晨颜
1.基于user表快速签发
from rest_framework_jwt.views import obtain_jwt_token
path('login/', obtain_jwt_token), # 快速签发
2.修改快速签发的过期时间,返回格式
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_RESPONSE_PAYLOAD_HANDLER': 'app01.utils.jwt_response_payload_handler',
}
#utils.py
def jwt_response_payload_handler(token, user=None, request=None):
return {'status': 100,'msg': '登录成功','username':user.username,'token': token}
3自己写签发
class UserView(ViewSet):
@action(methods=['POST'], detail=False)
def login(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user:
# 通过user拿到payload
payload = jwt_payload_handler(user)
# 通过payload拿到token
token = jwt_encode_handler(payload)
return Response({'code': 100, 'msg': '登录成功', 'token': token})
return Response({'code': 101, 'msg': '用户名或密码错误'})
4.注册普通用户
如果,直接注册,则密码明文表示,想要密文表示,需要make_password
方法1
#views
class UserView(ViewSet):
from rest_framework.decorators import action
@action(methods=['POST'], detail=False)
def register(self,request):
username = request.data.get('username')
password = request.data.get('password')
userobj=User.objects.filter(username=username)
if userobj:return Response({'code':101,'msg':'用户名存在'})
User.objects.create(username=username,password=password)
return Response({'code': 100, 'msg': 'ok'})
#modles
class User(AbstractUser):
mobile=models.CharField(max_length=11)
password = models.CharField(max_length=128)
def save(self, *args, **kwargs):
from django.contrib.auth.hashers import make_password
self.password=make_password(self.password)
super().save(*args, **kwargs)
方法2,直接在视图类加密密码
class UserView(ViewSet):
from rest_framework.decorators import action
@action(methods=['POST'], detail=False)
def register(self,request):
username = request.data.get('username')
password = request.data.get('password')
from django.contrib.auth.hashers import make_password
password=make_password(password)
userobj=User.objects.filter(username=username)
if userobj:return Response({'code':101,'msg':'用户名存在'})
User.objects.create(username=username,password=password)
return Response({'code': 100, 'msg': 'ok'})
tooken校验#重点看,还没有吃透
# JWTAuthentication.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt
from rest_framework_jwt.settings import api_settings
from .models import User
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class JWTAuthentication(BaseAuthentication):
def authenticate(self, request):
token=request.META.get("HTTP_TOKEN")#{'user_id': 1, 'username': 'zs', 'exp': datetime.datetime(2023, 5, 30, 11, 18, 56, 707060), 'email': '4@qq.com'}
try:
payload=jwt_decode_handler(token)
user_id = payload.get('user_id')
# 每个需要登录后,才能访问的接口,都会走这个认证类,一旦走到这个认证类,机会去数据库查询一次数据,会对数据造成压力
#####重点看下面推导过程
# 1.
# user = User.objects.get(pk=user_id)
# 2
# user={'username': payload.get('user_username'),'id':user_id}
# 3
user=User(username=payload.get('username'),id=user_id)
print(user.username,user.id)
except jwt.ExpiredSignature:raise AuthenticationFailed('token过期')
except jwt.DecodeError:raise AuthenticationFailed('解码失败')
except jwt.InvalidTokenError:raise AuthenticationFailed('token认证异常')
except Exception:raise AuthenticationFailed('token认证异常')
return user, token
继承djangouser表
setting.py
AUTH_USER_MODEL = 'app01.User'
from django.contrib.auth.models import AbstractUser