【问题标题】:Drf how to: simple-jwt authenticating without the USERNAME_FIELDDrf 如何:没有 USERNAME_FIELD 的 simple-jwt 身份验证
【发布时间】:2022-01-20 03:54:28
【问题描述】:

我已经扩展了 TokenObtainPairSerializer,我的用户模型将电子邮件作为 USERNAME_FIELD,但这种类型的用户没有电子邮件,而是我想使用自动生成的唯一 ID 来代替电子邮件进行身份验证。

class MyTokenStudentSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        user = authenticate()(
            student_id=attrs['student_id'], password=attrs['password'])
        if user is not None:
            if user.is_active:
                data = super().validate(attrs)
                refresh = self.get_token(self.user)
                refresh['student_id'] = self.user.student_id
                try:
                    data["refresh"] = str(refresh)
                    data["access"] = str(refresh.access_token)
                    data['student_id'] = self.user.student_id
                    data['firstname'] = self.user.firstname
                    data['middlename'] = self.user.middlename
                    data['lastname'] = self.user.lastname
                    data['phone'] = self.user.phone
                    data['last_login'] = self.user.last_login
                    data['joined_date'] = self.user.joined_date
                except Exception as e:
                    raise serializers.ValidationError(
                        {'error': 'Something Wrong!'})
                return data
            else:
                raise serializers.ValidationError(
                    {'error': 'Account is not activated'})
        else:
            raise serializers.ValidationError({
                'error': 'Incorrect student id and password combination!'})

即使我没有通过电子邮件字段,这需要电子邮件和密码,我如何让它接受 student_id 而不是电子邮件。

【问题讨论】:

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


    【解决方案1】:

    您可以按如下方式覆盖username_field

    还要小心使用 PasswordField,它默认会修剪空白。您绝对不希望 password 有效。

    from rest_framework import serializers
    rest_framework_simplejwt.serializers import PasswordField
    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    
    class MyTokenStudentSerializer(TokenObtainPairSerializer):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['student_id'] = serializers.CharField(required=False)
            self.fields['password'] = PasswordField(trim_whitespace=False)
    
        username_field = 'student_id'
        auth_fields = ['student_id']
    

    【讨论】:

    • 它有效,但我如何传递附加数据以及您在我的问题中看到的响应?
    • 可以将结果累加到自定义的Serializer中,例如:student = StudentSerializer(user_obj).data嵌套结果。
    • 你能告诉我更多代码吗,或者告诉我 (user_obj) 做了什么以及如何从序列化字段中获取数据
    • 诀窍是嵌套一个序列化程序。更多参考头here
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2016-01-02
    • 2020-01-27
    • 2023-03-31
    • 2017-10-18
    • 1970-01-01
    • 2018-04-21
    • 2021-04-10
    相关资源
    最近更新 更多