【问题标题】:Django rest framework authenticationDjango REST框架身份验证
【发布时间】:2017-11-02 10:42:52
【问题描述】:

我想在 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

【问题讨论】:

    标签: python django python-3.x django-rest-framework django-rest-auth


    【解决方案1】:

    使用 as 来消除冲突。

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

    并在网址中使用它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
    

    【讨论】:

    • 我只在 URL 中添加了url(r'^api-token-auth/', views.obtain_auth_token)。我认为这就足够了,因为它是内置的。例如,我是否必须在我的视图中添加一些内容?
    • @Wahtdbogh 是的。你能包括你关于 Django restframwork 的设置吗?
    • 好的。现在你的问题是什么?我看到您已包含基本和会话身份验证。有效吗?
    • 我的问题是我只能登录超级用户,对于我数据库中的其他用户,我得到响应 - “无法使用提供的凭据登录。”
    • 好的,您是否尝试在 settings.py 文件中添加 ToekenAuthentication 类。
    【解决方案2】:

    您需要在您的settings.py 中包含TokenAuthentication 到您的DEFAULT_AUTHENTICATION_CLASSES

    来自文档,

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

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

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

    【讨论】:

    • 我加了还是一样的问题。
    • 你是如何创建用户的?通过管理站点??
    • 我已经解决了我的问题。我认为问题不是数据库中的加密密码,@RajaSimon 帮助我在序列化程序中更改它。
    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多