【问题标题】:How to store simplejwt token into database如何将 simplejwt 令牌存储到数据库中
【发布时间】:2020-03-15 18:10:06
【问题描述】:

我正在使用 django-rest-framework-simplejwt 进行用户注册。

按照本教程enter link description here

我的代码如下:

class RegistrationSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        style={'input_type': 'password'}, write_only=True,
    )
    password2 = serializers.CharField(
        style={'input_type': 'password'},max_length=20
    )
    tokens = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        fields = ['username', 'email', 'password', 'password2', 'tokens']

    def get_tokens(self, user):
        user = UserProfile(
            email=self.validated_data['email'],
            username=self.validated_data['username']
        )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        user.set_password(password)
        tokens = RefreshToken.for_user(user)
        refresh = text_type(tokens)
        access = text_type(tokens.access_token)
        data = {
            "refresh": refresh,
            "access": access
        }
        return data

    def save(self):
        user = UserProfile(
            email=self.validated_data['email'],
            username=self.validated_data['username']
        )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        user.set_password(password)
        user.save()
        return user

在视图中:

class UserCreateView(generics.CreateAPIView):
    '''create user'''
    serializer_class = RegistrationSerializer

问题是每次创建用户,我都可以得到2个两个token的返回,但是在数据库中我找不到token。

所以我想我没有存储它们,所以我应该存储令牌吗?

【问题讨论】:

    标签: django django-rest-framework jwt django-rest-framework-jwt django-rest-framework-simplejwt


    【解决方案1】:

    JWT 可用于无数据库身份验证。因为它在令牌中对身份验证所需的数据进行编码。您的应用将能够在解码包含嵌入数据的令牌后对用户进行身份验证。

    但是如果你想将令牌存储在simplejwt 中,你可以使用OutstandingingToken 模型在simplejwt 中实现将令牌存储在数据库中。

    在使用 OutstandingToken 之前,请确保将 rest_framework_simplejwt.token_blacklist 放入项目设置的 INSTALLED_APPS 列表中。

    【讨论】:

    • 很好的解决方案米拉德,谢谢! damet garm。
    猜你喜欢
    • 2017-12-25
    • 2021-05-18
    • 2021-05-20
    • 2018-11-12
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2014-12-08
    相关资源
    最近更新 更多