首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将simplejwt令牌存储到数据库中

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

Stack Overflow用户
提问于 2019-11-20 13:31:00
回答 1查看 670关注 0票数 0

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

遵循本教程enter link description here

我的代码如下:

代码语言:javascript
复制
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

视图中:

代码语言:javascript
复制
class UserCreateView(generics.CreateAPIView):
    '''create user'''
    serializer_class = RegistrationSerializer

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-11-22 20:25:57

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

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58947333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档