Django REST框架身份验证



我想在django中创建身份验证。我正在尝试按照此操作。不幸的是,目前我有两个问题。首先,当我尝试添加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

用来消除冲突。

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中。

来自文档,

要使用Tokenauthentication方案,您需要配置身份验证类以包括Tokenauthentication。

所以更改您的设置。这样,

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

最新更新