python - 在 django rest 框架中使用令牌身份验证返回更多信息
问题描述
我已经为我的 django 项目实现了令牌身份验证。在 POST 请求后为用户生成令牌时。我需要使用令牌返回其他信息,例如:
{
"令牌": "令牌字符串",
"电子邮件": "email@email.com",
“电话”:“12345”,“照片”:取决于照片序列化器
}
请问我该怎么做?这是我的代码:
模型.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()
视图.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",
)
序列化程序.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 类的 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
})
推荐阅读
- windows - 在 WinSCP 中同步文件掩码 - 将文件过滤器与子目录排除合并
- android - android workmanager 中 RxWorker 的 Observable
- c# - 如何创建每 40 毫秒更新一次并与服务器端方法同步的高速计数器
- python - 来自 tfd.Distribution.sample 的复杂 event_shape
- python - 如何使用混淆矩阵计算自定义训练的 spacy ner 模型的整体准确性?
- sql-server - SQL 使用 With 子句连接查询
- elasticsearch - Elasticsearch 分析器不会替换撇号 (')
- c# - 如何使列表项的一部分可选择和其他不可选择的wpf
- android - 有没有办法让某些产品口味没有 google-services.json?
- ag-grid - 隐藏列时,ag-grid 无法移动组列