【发布时间】: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