在 django rest 框架中使用令牌身份验证返回更多信息
returning more informations with token authentication in django rest framework
我已经为我的 Django 项目实现了令牌认证。在 POST 请求后为用户生成令牌时。我需要使用令牌 return 其他信息
喜欢:
{
"令牌": "令牌字符串",
"电子邮件": "电子邮件@email.com",
"phone": "12345",
“照片”:取决于照片序列化器
}
请问我该怎么做?这是我的代码:
Models.py
class User(AbstractUser):
username = None
email = models.EmailField(max_length=100,
verbose_name='email', unique=True)
phone = models.CharField(max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
Views.py
class AuthToken(auth_views.ObtainAuthToken):
serializer_class = AuthTokenSerializer
if coreapi is not None and coreschema is not
None:
schema = ManualSchema(
fields=[
coreapi.Field(
name="email",
required=True,
location='form',
schema=coreschema.String(
title="Email",
description="Valid email
for authentication",
),
),
coreapi.Field(
name="password",
required=True,
location='form',
schema=coreschema.String(
title="Password",
description="Valid password for authentication",
),
),
],
encoding="application/json",
)
Serializers.py
class AuthTokenSerializer(serializers.Serializer):
email = serializers.EmailField(label=_("Email"))
password = serializers.CharField(
label=_("Password",),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user =
authenticate(request=self.context.get('request'),
email=email, password=password)
if not user:
msg = ('Unable to log in with
provided credentials.')
raise
serializers.ValidationError(msg,
code='authorization')
else:
msg = ('Must include "username" and
"password".')
raise serializers.ValidationError(msg,
code='authorization')
attrs['user'] = user
return attrs
class UserSerializer(serializers.ModelSerializer):
photo = PhotoSerializer()
class Meta:
model = User
fields = ['id', 'email','phone', 'photo', ']
只需覆盖 auth_views.ObtainAuthToken class 的 post 函数并将您的数据添加到响应:
class AuthToken(auth_views.ObtainAuthToken):
serializer_class = AuthTokenSerializer
if coreapi is not None and coreschema is not
None:
schema = ManualSchema(
fields=[
coreapi.Field(
name="email",
required=True,
location='form',
schema=coreschema.String(
title="Email",
description="Valid email
for authentication",
),
),
coreapi.Field(
name="password",
required=True,
location='form',
schema=coreschema.String(
title="Password",
description="Valid password for authentication",
),
),
],
encoding="application/json",
)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'email': user.email,
# and your extra data required
})
我已经为我的 Django 项目实现了令牌认证。在 POST 请求后为用户生成令牌时。我需要使用令牌 return 其他信息 喜欢:
{
"令牌": "令牌字符串",
"电子邮件": "电子邮件@email.com",
"phone": "12345", “照片”:取决于照片序列化器
}
请问我该怎么做?这是我的代码:
Models.py
class User(AbstractUser):
username = None
email = models.EmailField(max_length=100,
verbose_name='email', unique=True)
phone = models.CharField(max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
Views.py
class AuthToken(auth_views.ObtainAuthToken):
serializer_class = AuthTokenSerializer
if coreapi is not None and coreschema is not
None:
schema = ManualSchema(
fields=[
coreapi.Field(
name="email",
required=True,
location='form',
schema=coreschema.String(
title="Email",
description="Valid email
for authentication",
),
),
coreapi.Field(
name="password",
required=True,
location='form',
schema=coreschema.String(
title="Password",
description="Valid password for authentication",
),
),
],
encoding="application/json",
)
Serializers.py
class AuthTokenSerializer(serializers.Serializer):
email = serializers.EmailField(label=_("Email"))
password = serializers.CharField(
label=_("Password",),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user =
authenticate(request=self.context.get('request'),
email=email, password=password)
if not user:
msg = ('Unable to log in with
provided credentials.')
raise
serializers.ValidationError(msg,
code='authorization')
else:
msg = ('Must include "username" and
"password".')
raise serializers.ValidationError(msg,
code='authorization')
attrs['user'] = user
return attrs
class UserSerializer(serializers.ModelSerializer):
photo = PhotoSerializer()
class Meta:
model = User
fields = ['id', 'email','phone', 'photo', ']
只需覆盖 auth_views.ObtainAuthToken class 的 post 函数并将您的数据添加到响应:
class AuthToken(auth_views.ObtainAuthToken):
serializer_class = AuthTokenSerializer
if coreapi is not None and coreschema is not
None:
schema = ManualSchema(
fields=[
coreapi.Field(
name="email",
required=True,
location='form',
schema=coreschema.String(
title="Email",
description="Valid email
for authentication",
),
),
coreapi.Field(
name="password",
required=True,
location='form',
schema=coreschema.String(
title="Password",
description="Valid password for authentication",
),
),
],
encoding="application/json",
)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'email': user.email,
# and your extra data required
})