标签: django-rest-auth

Django + DRF:403 FORBIDDEN:CSRF令牌丢失或不正确

我有一个Android客户端应用程序尝试使用Django + DRF后端进行身份验证.但是,当我尝试登录时,我得到以下响应:

403: CSRF Failed: CSRF token missing or incorrect.
Run Code Online (Sandbox Code Playgroud)

该请求将发送给http://localhost/rest-auth/google/以下机构:

access_token: <the OAuth token from Google>
Run Code Online (Sandbox Code Playgroud)

什么可能导致这个?客户端没有CSRF令牌,因为要进行身份验证的POST是客户端和服务器之间首先发生的事情.我检查了很多过去的问题同样的问题,但我找不到任何解决方案.

Django方面的相关设置如下:

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend"
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
    "django.contrib.auth.context_processors.auth",
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount"
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.google',

    'django.contrib.admin',

    # REST framework
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ( 
        'rest_framework.permissions.IsAuthenticated'
    ),
}
Run Code Online (Sandbox Code Playgroud)

django csrf django-rest-framework django-allauth django-rest-auth

4
推荐指数
2
解决办法
4244
查看次数

有什么办法可以更改登录的Django-rest-auth的视图吗?

我使用Django-rest-auth创建了rest API,在登录时,它返回键和一些用户信息,但是我需要添加一些状态,例如成功和消息等。有什么方法可以覆盖django-rest-auth的视图进行登录吗?

class TokenSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)  # this is add by myself.
    device = DeviceSerializer(many=True, read_only=True)

    class Meta:
        model = TokenModel
        fields = ('key', 'user', 'device',)
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-rest-auth

4
推荐指数
1
解决办法
1658
查看次数

django rest-auth获取用户个人资料

我有点失落......我正在尝试开发一个离子应用程序,需要进行身份验证,而不是Django Web应用程序.

我安装了Django-Rest-Framework和Django-Rest-Auth.我能够登录,使用令牌获取用户,但我如何检索更多用户数据?

url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-token-auth/$',obtain_auth_token),
Run Code Online (Sandbox Code Playgroud)

在host.com/rest-auth/user/ url中使用Django-rest-auth我只有这些数据:

HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, PUT, HEAD, OPTIONS, PATCH

{
    "username": "ikerib",
    "email": "ikerib@gmail.com",
    "first_name": null,
    "last_name": null
}
Run Code Online (Sandbox Code Playgroud)

但我需要更多!像id,user_photo,city ...

我尝试像这样配置用户序列化程序:

from rest_framework import serializers
from gamer.models import GamerUser

class GameUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = GamerUser
        fields = ('id', 'fullname', 'get_photo', 'karma')
Run Code Online (Sandbox Code Playgroud)

而这个观点:

@csrf_exempt
def gameuser_detail(request, pk):
    try:
        gameuser = GameUser.objects.get(pk=pk)
    except GameUser.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = GameUserSerializer(gameuser)
        return JSONResponse(serializer.data)
Run Code Online (Sandbox Code Playgroud)

但我无法获取用户数据,因为我不知道用户ID ..

任何帮助或线索??? …

django rest django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
2590
查看次数

Django休息登记

我在我的django项目中使用Django-rest-auth(https://github.com/Tivix/django-rest-auth)进行登录和注册.我看到一个默认的注册表格如下:

在此输入图像描述

目前,我可以使用电子邮件而不是用户名注册新用户.我的MySql数据库中的默认auth_user表包含以下列:(id,password,last_login,is_superuser,username,first_name,last_name,email,is_staff,is_active,date_joined)

我的settings.py:

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
#Rest-auth
'rest_framework.authtoken',
'rest_auth',
#Rest-auth registration
'allauth',
'allauth.account',
'rest_auth.registration',
#Following is added to allow cross domain requests i.e. for serving requests those are coming from frontend app 
'corsheaders',
'flights',
)
Run Code Online (Sandbox Code Playgroud)

我想修改我的注册表单,使其具有上面字段的名字和姓氏,这样当我注册一个新用户时,这两列也会填充first_name和last_name.目前我没有其他注册视图或任何自定义用户模型,我只是使用django-rest-auth提供的API端点.

我怎样才能做到这一点?

django django-rest-framework django-allauth django-rest-auth

3
推荐指数
1
解决办法
1210
查看次数

django rest 框架 csrf 令牌丢失或不正确

你好,我正在使用 django rest-auth,我在 /password/change/ 中遇到了这个问题,它总是返回 csrf 令牌丢失或不正确的问题:我正在向一个 android 应用程序发出请求,我正在开发我的设置是:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',

'rest_framework',
'rest_framework.authtoken',

'rest_auth',
'rest_auth.registration',

'allauth',
'allauth.account',
'allauth.socialaccount',
Run Code Online (Sandbox Code Playgroud)

]

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

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}
Run Code Online (Sandbox Code Playgroud)

版本:django-rest-auth==0.9.1

djangorestframework==3.6.2

django django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
7538
查看次数

未提供身份验证凭据 django-rest-auth

我有一个应用程序,我实现了 django restframework 和 django reat-auth 和 jango 框架 jwt。我按照说明操作,在浏览器中一切正常。我现在决定在邮递员中测试连接并尝试获取端点所在的登录用户详细信息,/rest-auth/user但出现以下错误

{ "detail": "Authentication credentials were not provided." }

我决定复制返回的令牌并将其放在用户 url 的标题中

"Authorization": "Token ahagjbeghq7hbcvgqhvwqu08hevug.jwhhwiiwhw",
"Content-Type": "application/json; charset=utf-8"
Run Code Online (Sandbox Code Playgroud)

使用返回的令牌修改标题后,我希望它显示用户的详细信息,但我仍然得到

{
    "detail": "Authentication credentials were not provided."
}
Run Code Online (Sandbox Code Playgroud)

但是我可以通过restframework jwt提供的url来验证token是否正确

/api-token-verify这将返回令牌值。这是我的 django rest 身份验证类

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

    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',

    ),

}
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
7499
查看次数

如何在DRF + django-rest-auth中使用自定义用户模型保存有关注册的额外字段

使用带有django-rest-auth的Django REST Framework(DRF),我创建了一个带有一个额外字段的自定义用户模型。我的目标是使用django-rest-auth注册端点在一个请求中注册一个新用户,从而发送所有数据以创建一个新用户,包括多余字段的数据。

我正在使用AbstractUser,因为它似乎是推荐给初学者的,在初学者中,更高级的开发人员可以使用AbstractBaseUser。这也是为什么以下SO答案对于我想要实现的目标而言过于复杂的原因:链接此处

我知道这个问题已经被问过多次了,但是答案并不完全是我想要的。对于像我这样的初学者来说,这是一件复杂的事情。

所以,我的问题是,任何人都可以解释如何实现我想要的吗?

我在用:

Django              2.1.4
django-allauth      0.38.0
django-rest-auth    0.9.3
djangorestframework 3.9.0
Run Code Online (Sandbox Code Playgroud)

这是到目前为止的代码:

使用本教程来获得此代码

settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!gxred^*penrx*qlb=@p)p(vb!&6t78z4n!poz=zj+a0_9#sw1'

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

ALLOWED_HOSTS = [] …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-allauth django-rest-auth

3
推荐指数
2
解决办法
1403
查看次数

如何从 django userchangeform 的登录页面中删除用户名字段

登录页面中有三个字段(用户名、电子邮件、密码),但我只想要两个字段(电子邮件、密码)。如何从登录页面中删除用户名字段。提前致谢

模型.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    name = models.CharField(max_length=255)

    def __str__(self):
    return self.email
Run Code Online (Sandbox Code Playgroud)

表格.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('username','email')

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields
Run Code Online (Sandbox Code Playgroud)

序列化程序.py

from rest_framework import serializers
from . import models

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CustomUser
        fields = ('email', 'username', )
Run Code Online (Sandbox Code Playgroud)

python django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
1664
查看次数

如何测试使用 django-rest-auth 令牌身份验证的 api?

我使用 django-rest-auth 进行身份验证并使用它提供的令牌进行授权。我也使用了 django-rest 提供的一些 permission_class。在我的每个方法之前,我都在 views.py 中进行了跟踪。

视图.py

@api_view(['GET'])
@authentication_classes((TokenAuthentication))
@permission_classes((permissions.IsAuthenticated,))
Run Code Online (Sandbox Code Playgroud)

我如何在测试这些 api 时进行身份验证以访问 views.py 中的该方法。因为没有身份验证它会禁止 403。如何在测试中模拟身份验证。

django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
1513
查看次数

Django-rest-auth (dj-rest-auth) 自定义用户注册

我正在使用 dj-rest-auth ( https://dj-rest-auth.readthedocs.io/en/latest/ ) 并尝试实现自定义注册表单。当我尝试注册新用户时,我有基本表单。我在旧版本 ( https://django-rest-auth.readthedocs.io/en/latest/ ) 中看到,如果您使用 password1 和 password2,则不必重新键入所有代码。

序列化程序.py

from rest_framework import serializers
from dj_rest_auth.registration.serializers import RegisterSerializer


class CustomRegisterSerializer(RegisterSerializer):
first_name = serializers.CharField()
last_name = serializers.CharField()

def get_cleaned_data(self):
    super(CustomRegisterSerializer, self).get_cleaned_data()
    return {
        'username': self.validated_data.get('username', ''),
        'password1': self.validated_data.get('password1', ''),
        'password2': self.validated_data.get('password2', ''),
        'email': self.validated_data.get('email', ''),
        'first_name': self.validated_data.get('first_name', ''),
        'last_name': self.validated_data.get('last_name', '')
    }
Run Code Online (Sandbox Code Playgroud)

设置.py

REST_AUTH_SERIALIZERS = {
'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer',
}
Run Code Online (Sandbox Code Playgroud)

authentication django django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
3650
查看次数