我使用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问题是每次我创建一个用户,我都可以得到两个令牌的返回值,但是在数据库中我找不到这个令牌。
所以我猜我没有存储它们,那么我应该存储令牌吗?
发布于 2019-11-22 20:25:57
JWT可用于无数据库身份验证。因为它将认证所需的数据编码到令牌中。你的应用程序将能够在解码嵌入了数据的令牌后对用户进行身份验证。
但是,如果你想在simplejwt中存储令牌,你可以使用simplejwt中实现的OutstandingingToken模型将令牌存储在数据库中。
在使用OutstandingToken之前,请确保将rest_framework_simplejwt.token_blacklist放入项目设置的INSTALLED_APPS列表中。
https://stackoverflow.com/questions/58947333
复制相似问题