搜索

Django实现jwt方式登录

染念染念

jwt的概念这边就不再阐述了,就是cookie的替代品

view.py

import jwt
import datetime

from rest_framework.decorators import api_view
from rest_framework.response import Response
import learn.utils as tool

# Create your views here.
from fingercode import settings
from learn.models import User
from learn.serializers import UserSerializer


@api_view(('GET', 'POST'))
def login(request):
    if request.method == 'POST':
        username = request.data.get('username')
        password = request.data.get('password')
        if username and password:
            try:
                if not request.META.get('HTTP_AUTHORIZATION', ''):
                    password = tool.md5(password)
                    # user_data = User.objects.get(username=username, password=password)
                    user_dict = UserSerializer(User.objects.filter(username=username, password=password), many=True)
                    payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1), 'data': user_dict.data}
                    headers = {
                        "type": "jwt",
                        "alg": "HS256"
                    }
                    token = jwt.encode(payload, settings.SECRET_KEY, headers=headers).decode()
                    return Response({'data': token})
                else:
                    authorization = request.META.get('HTTP_AUTHORIZATION', '')
                    auth = authorization.split()
                    # 验证头信息的token信息是否合法
                    if not auth:
                        return Response({'msg': '未获取到Authorization请求头'})
                    if auth[0].lower() != 'jwt':
                        return Response({'msg': 'Authorization请求头中认证方式错误'})
                    if len(auth) == 1:
                        return Response({'msg': "非法Authorization请求头"})
                    elif len(auth) > 2:
                        return Response({'msg': "非法Authorization请求头"})
                    token = auth[1]
                    payload = jwt.decode(token, settings.SECRET_KEY)
                    return Response({'msg': payload})
            except User.DoesNotExist:
                return Response({'msg': '用户名或者密码错误'})
    else:
        return Response(status=404)

models.py

自定义吧,我感觉这个没啥关系,我的就是一个关于user的数据表

serializers.py

from rest_framework import serializers

from learn.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ('password', )

接下来通过包含请求头访问

QQ截图20200805162919.png
如果不包含

QQ截图20200805162956.png

遇到的bug:

看views.py ,request.POST.get不适用api的post接收,感觉是表单的post提交,而要使用request.data.get才能正确接收到post的值,这里我吃了大亏

查看目录

目录

来自 《Django实现jwt方式登录》

    评论区


    2 条评论

    1. Alex
      2020年08月06日

      djangorestframework-jwt了解一波


      1. 染念作者
        2020年08月07日
        @Alex

        @(吐舌)



    可能感兴趣