Django 休息框架身份验证

Django rest framework authentication

我想在 Django 中创建身份验证。我正在尝试根据 this 做所有事情。 不幸的是,此刻我有两个问题。首先,当我尝试添加 from rest_framework.authtoken import views 时,我与 from companies import views 发生了冲突。我需要从 authtoken 到 url(r'^api-token-auth/', views.obtain_auth_token) 的视图。其次,当我使用 /api-token-auth/ 时,我的问题是我只能登录超级用户,对于我数据库中的其他用户,我得到响应 - "Unable to log in with provided credentials."

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'companies.apps.CompaniesConfig',
    'rest_framework.authtoken'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'pri.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'pri.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pri',
        'USER': 'root',
        'HOST': '127.0.0.1',
    }
}

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


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/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.11/howto/static-files/

STATIC_URL = '/static/'

CORS_ORIGIN_ALLOW_ALL = True

使用 as 来消除冲突。

from companies import views as companies_views
from rest_framework.authtoken import views as rest_auth_views

并在 url 中使用它 url(r'^api-token-auth/', rest_auth_views.obtain_auth_token)

提供的详细信息不足以调试导致身份验证的原因。您能否提供更多有关基于令牌的身份验证的代码。

更新:

与OP沟通后。他使用 UserSerializer 创建了用户,并将密码保存为纯文本。并且身份验证不起作用。

class UserSerializer(serializers.ModelSerializer): 

    class Meta: 
        model = User 

        fields = '__all__'`

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

您需要在 settings.py 中将 TokenAuthentication 添加到 DEFAULT_AUTHENTICATION_CLASSES

来自文档,

To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication.

所以像这样改变你的settings.py,

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