【发布时间】:2018-03-28 06:15:29
【问题描述】:
我是 Python 和 Django REST 框架的新手,我正在尝试使用 JWT (https://jpadilla.github.io/django-rest-framework-jwt/) 配置身份验证。我可以在注册时为用户创建一个令牌,但是当我尝试通过我的 api 进行身份验证时出现“无效签名”错误。我已经在https://jwt.io/ 确认了错误。这似乎意味着我的令牌创建不正确。有什么想法吗?
这是我的配置:
from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
username = models.CharField(max_length=45, unique=True)
phone = models.CharField(max_length=20)
password = models.CharField(max_length=100, blank=False, default='')
from rest_framework import serializers
from . models import User
from django.contrib.auth.hashers import make_password
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'username', 'phone',
'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
# the create method creates and saves an object in a single statement
user = User.objects.create(
first_name = validated_data['first_name'],
last_name = validated_data['last_name'],
username = validated_data['username'],
phone = validated_data['phone'],
password = make_password(validated_data['password']),
)
return user
from joyrides_api.models import User
from joyrides_api.serializers import UserSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework_jwt.utils import jwt_payload_handler
from rest_framework import permissions
from rest_framework_jwt.settings import api_settings
from rest_framework.permissions import AllowAny
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class UserList(APIView):
permission_classes = (AllowAny,)
# this method creates the user
def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
# the save method calls serializer's create method
user = serializer.save()
if user:
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
json = serializer.data
json['token'] = token
return Response(json, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
【问题讨论】:
标签: django authentication django-rest-framework jwt