【问题标题】:Unable to get authorization token of a User无法获取用户的授权令牌
【发布时间】:2018-12-21 18:31:48
【问题描述】:

在我的 django-rest-application 中,我使用 post 方法成功注册了一个用户。但是,当我尝试登录或获取用户的授权令牌时,我收到未授权错误。

我正在使用 post_save 接收器更新令牌数据库,如下所示。

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

即使我在 python shell 中检查模型时,我也可以通过以下方法成功验证用户和令牌数据。

from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

user = User.objects.get(username='user1')
token = Token.objects.get(user__username='user1')

user.password 和 token 数据经过验证并存在。并且用户是活跃的。但是,我无法使用 curl 方法获取授权令牌。即使我无法使用凭据登录浏览器。

卷曲请求

curl -X POST http://127.0.0.1:8000/api-token-auth/ -d "username=user1&password=password"

我的 settings.py 文件如下所示。

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'c8x*pc%c$0-_k-wx5&u42m3k8k1jv!^o27&-*1w3u*v!ut3-5b'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.staticfiles',
    # Rest Framework app
    'rest_framework',
    'rest_framework.authtoken',
    # Internal Apps
    'src.main',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',

    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
ROOT_URLCONF = 'market_place.urls'

WSGI_APPLICATION = 'market_place.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

我错过了什么?

修改 curl 命令出错

{
    "non_field_errors": [
        "Unable to log in with provided credentials."
    ]
}

我的用户资料模型如下:

class UserProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(upload_to="user_profile_pic", null=True)




class UserProfileRegisterView(generics.CreateAPIView):
    serializer_class = UserProfileSerializer

    permission_classes = [
        permissions.AllowAny  # Or anon users can't register
    ]

【问题讨论】:

  • 你的 curl 命令没有问题。我在我的系统上申请并获得了令牌。如果您无法使用您的凭据登录,则意味着您的凭据存在问题。你能分享一下你是如何注册用户的代码吗?
  • 你得到的错误是什么?发表它。同样,应该在登录期间创建令牌,而不是在创建用户时创建。用户可以根据他登录的设备数量来使用多个令牌
  • 登录(或授权令牌)视图是自定义视图还是来自 DRF 的视图?如果是自定义视图,请发布代码
  • 为了登录,我试图在浏览器中发出 API 请求。视图集仅对授权用户具有权限。因此浏览器会弹出一个登录页面。我在那里提供凭证。我没有任何用于登录的视图集。
  • 对于 auth-toke,我正在使用来自 rest_framework.authtoken.views 的视图获取_auth_token。

标签: django django-rest-framework django-views


【解决方案1】:

如果您发布的内容就是您的用户创建视图的全部内容,那么这就是问题所在。出于明显的安全原因,密码在 Django 中不以纯格式存储。相反,它们的哈希值被存储,并且在登录期间,输入密码的哈希值与存储的哈希值进行比较。

从您发布的代码来看,密码似乎是以明文形式存储的,因此当身份验证器尝试比较发送的密码的哈希值和存储的输入时,它们不匹配。

您应该使用user.set_password() 来确保它被正确地散列和保存。

你的UserProfileSerializer 的create() 方法应该是这样的:

def create(self, validated_data):
    password = validated_data.pop('password')
    instance = super().create(validated_data)
    instance.user.set_password(password)

    instance.user.save()
    return instance

当然,如何创建配置文件和用户的详细信息超出了此代码的范围,因为我不知道您的 UserProfileSerializer 是如何定义的,但这应该可以让您大致了解。 如果您在创建配置文件的同时创建用户对象,那么 create 方法看起来会稍微复杂一些。查看 DRF 的 writable nested serializers 了解如何实现这一目标的详细信息

【讨论】:

  • 感谢 Ken4scholars。我到了我做错的地方。这工作得很好。
猜你喜欢
  • 2019-06-19
  • 2012-10-14
  • 2019-05-18
  • 2019-12-09
  • 2018-09-15
  • 1970-01-01
  • 2015-05-04
  • 2015-10-11
  • 1970-01-01
相关资源
最近更新 更多