如何将simplejwt令牌存储到数据库中

时间:2019-11-20 05:31:00

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

我正在使用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

问题是,每次创建用户时,我都能获得这两个两个令牌的返回,但是在数据库中找不到该令牌。

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

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题