首页 > 解决方案 > 在 django 中面临自定义用户身份验证和 oauth2 的问题

问题描述

我正在制作一个具有受保护 API 的应用程序,并且只有经过身份验证的用户才能访问它。为了利用 django 强大的身份验证,我决定用一些额外的字段扩展它的用户模型并进行定制。我通过扩展 AbstractUser 模型来使用自定义用户模型。但是在请求 oauth2 令牌时面临以下问题。下面是我的代码:

class MyUser(AbstractUser):
    """Extended version of Django User Model"""
    is_email_verified = models.BooleanField(
        verbose_name="Email Verified?",
        default=False, choices=T_N_F_CHOICES, auto_created=True,
        help_text="This flag indicates if the email address is authentic and validated"
    )
    mobile = PhoneNumberField(
        verbose_name="Phone Number", blank=True, null=True, unique=True
    )
    is_mobile_verified = models.BooleanField(
        verbose_name="Mobile Verified?",
        default=False, choices=T_N_F_CHOICES, auto_created=True,
        help_text="This flag indicates if the mobile number is authentic and validated"
    )
    profile_pic = models.ImageField(
        verbose_name="Profile Picture",
        upload_to=settings.UPLOAD_DIR,
        height_field=None,
        width_field=None,
        max_length=None,
        blank=True,
        null=True
    )

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ['mobile']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

    class Meta:
        managed = True
        db_table = "MyUser"
        verbose_name = "MyUser"
        verbose_name_plural = "MyUsers"

设置.py

...
AUTH_USER_MODEL = 'users.AlphaslateUser'
CORS_ORIGIN_ALLOW_ALL = True
...
INSTALLED_APPS = [
    ...
    'oauth2_provider',
    'corsheaders',
    'countries_plus',
    'rest_framework',
    'users',
]
...
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ]
}
...
AUTHENTICATION_BACKENDS = (
    'oauth2_provider.backends.OAuth2Backend',
    'django.contrib.auth.backends.ModelBackend'
)
...
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
]

当我从令牌 url 请求令牌时,我面临以下错误。

Internal Server Error: /o/token/
Traceback (most recent call last):
...
packages/oauthlib/common.py", line 436, in __getattr__
    raise AttributeError(name)
AttributeError: get_full_path

如果有人知道如何解决。我会感激的。

标签: pythondjango

解决方案


这是 outhlib 代码版本 1.3.0 中的问题,请参阅我了解这一点的线程。我将版本降级到 1.2.0,问题得到解决。


推荐阅读