“细节:签名无效。”在JWT

时间:2017-11-02 10:53:40

标签: python django django-rest-framework jwt

我使用DRF和JWT令牌创建了登录/注册API。 api工作正常,它会生成令牌。现在我有另一个应用程序,它提供了仅向经过身份验证的用户添加通知的功能。 当我尝试测试时,我在邮递员中提供标题为Authorization JWT <token>,但我得到以下错误:

"detail : Invalid signature ."

我甚至检查了token此处https://jwt.io/,它显示了signature verified

现在我无法发现问题。我在互联网上冲浪但没有运气。请有人帮我解决这个问题。

对于完整的api,您可以在github here中看到它,并建议我,如果我在任何地方都错了。

views.py

class AddNotice(APIView):

    permission_class = (AllowAny,)
    serializer_class = AddNoticeSerializer
    def post(self, request, format=None):
        data = request.data
        serializer = AddNoticeSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

serializers.py

class AddNoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Api
        fields = ('id', 'notice_name', 'notice_desc', 'notice_author', 'notice_valid_till', 'notice_publish_date')

    def create(self, validated_data):
            return Api.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.notice_name =  validated_data.get('name', instance.notice_name)
        instance.notice_desc = validated_data.get('category', instance.notice_desc)
        instance.notice_author = validated_data.get('subcategory', instance.notice_author)
        instance.notice_valid_till = validated_data.get('subcategory', instance.notice_valid_till)
        instance.notice_publish_date = validated_data.get('subcategory', instance.notice_publish_date)
        instance.save()
        return instance

更新

我在邮递员那里试过。像这样的东西

enter image description here

2 个答案:

答案 0 :(得分:3)

问题是您没有在经理中定义get_by_natural_key方法。

这是库用于检索用户对象的方法: https://github.com/GetBlimp/django-rest-framework-jwt/blob/0a0bd402ec21fd6b9a5f715d114411836fbb2923/rest_framework_jwt/authentication.py#L59

要解决此问题,只需将此方法添加到AccountManager

即可
def get_by_natural_key(self, username):
    return self.get(username=username)

不确定为什么在django-rest-framework-jwt docs ..

中没有更详细地记录这一点

答案 1 :(得分:0)

发现在创建自定义用户模型时出现“无效签名”错误。我通过以下方法解决了这个问题:

基于Django的用户模型实例化模型:

``

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
.....

``

在settings.py中,使用AUTH_USER_MODEL指向自定义用户模型。

``

AUTH_USER_MODEL = 'user.User'

``

其中“ user.User”指向用户应用程序中的用户模型。

继续进行令牌生成。令牌将立即生效。