我_1661560_尝试使用JWT(http://getblimp.github.io/django-rest-framework-jwt/)配置身份验证 . 当我尝试通过我的api进行身份验证时,我收到了"Invalid Signature"错误 . 我在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)
2 回答
你还需要指定
authentication_classes
. 让它为空,它应该工作 .我的问题是当我使用django.db.model创建方法创建用户时:
我还没有在django.contrib.auth.models的Django用户模型中创建用户,这是模型Django和JWT框架用于身份验证 . 对于一个初学者来说,这并不是那么简单,考虑到JWT与Django的普及(或者看起来如此),这并不是一个大问题 . 我想有人会告诉我,我应该花更多时间在文档中 .
我离题了,优雅的解决方法是通过扩展django.contribut.auth.models ' AbstractUser which (I believe) links the pertinent parts of your user model to Django'模型来定制您的用户模型 . 说明:https://docs.djangoproject.com/en/1.11/topics/auth/customizing/
我做的选项是启动并运行(虽然我计划尽快切换到自定义模型)是使用django.contrib.auth.models的create_user方法将用户对象保存到Django用户模型,该方法与create相同上面的方法,除了它保存到Django的用户模型 .