标签: django-authentication

如何在我的 Android 应用程序中使用 django 身份验证(django.contrib.auth)

我使用 Django 作为我的 Android 应用程序的后端。我一直在使用@csrf-exempt注释和我的观点来处理post请求,因为我在从android(VOLLEY LIBRARY)发送post请求时无法处理csrf验证。现在,我必须使用 django.contrib.auth 登录和注销方法,但是当我从 android 发送 post 请求时会话不起作用。

我曾尝试在android中使用我的请求启用cookie,但这也不起作用(启用cookie也没有解决csrf验证失败的问题)。我还尝试从对django的GET请求中获取csrf令牌( django.middleware.csrf - get_token),然后在我的帖子请求中将 csrf 令牌传递到标头(X-CSRF-TOKEN)中,这也不起作用。

我用来在android中启用cookie的代码:

CookieManager manager = new CookieManager();   
CookieHandler.setDefault(manager);
Run Code Online (Sandbox Code Playgroud)

所以,
1.我不知道如何在不使用android中的@csrf-exempt的情况下使用django脚本。
2.以及如何使用django登录android

django android django-authentication

5
推荐指数
1
解决办法
2446
查看次数

django 中的自定义身份验证不起作用

我是 django 新手,我想对用户进行身份验证,因此email我编写了一个自定义身份验证,如文档中所示,但它似乎没有被调用,我不知道我该怎么做?usernamepassword

设置.py

AUTHENTICATION_BACKENDS = ('accounts.backend.AuthBackend',)
Run Code Online (Sandbox Code Playgroud)

视图.py

def login(request):
    if request.method == 'POST':
        username_or_email = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username_or_email, password=password)
        print(user)
        if user is not None:
            return reverse('task:home')
        else:
            messages.error(request, "Username or password is invalid")
            return render(request, 'accounts/login.html')
    else:
         return render(request, 'accounts/login.html')
Run Code Online (Sandbox Code Playgroud)

后端.py

from django.contrib.auth.models import User
from django.db.models import Q


class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None …
Run Code Online (Sandbox Code Playgroud)

django django-authentication python-3.x

5
推荐指数
1
解决办法
3953
查看次数

获取“AuthStateMissing ...会话值状态丢失。” 当将 AtlassianOAuth2 与 Django 一起使用时要调用回调 URI

我试图在 Django 应用程序中设置 oauth2 身份验证。这是我的设置:

\n\n
*other parts ommited*\n# AUTH STUFF\n\nAUTHENTICATION_BACKENDS = (\n    \'social_core.backends.atlassian.AtlassianOAuth2\',\n    \'django.contrib.auth.backends.ModelBackend\',\n)\n\nSOCIAL_AUTH_ATLASSIAN_KEY = \' *my atlassian key here* \'\nSOCIAL_AUTH_ATLASSIAN_KEY_SECRET = \' *my atlassian secret key here* \'\nLOGIN_URL = \'/auth/login/atlassian-oauth2\'\nLOGIN_REDIRECT_URL = \'/\'\nLOGOUT_REDIRECT_URL = \'/\'\nSOCIAL_AUTH_URL_NAMESPACE = \'social\'\n\nSESSION_COOKIE_SECURE = False\n# i had to do that^, based on what i have read from\n# /sf/ask/2633211591/\n# but it still doesn\'t work, sadly...\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的登录页面视图:

\n\n
def index(request):\n    session_id = request.session.session_key\n    session_id = hashlib.sha256(str(session_id).encode(\'utf-8\')).hexdigest()\n    auth_url = \'https://auth.atlassian.com/authorize?audience=api.atlassian.com&client_id=*my_client_id_here*&scope=read%3Ajira-user%20read%3Ajira-work%20manage%3Ajira-project&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Fatlassian%2F&state=$\'+ session_id +\'&response_type=code&prompt=consent\'\n    print(auth_url)\n    context = {\n        \'message\': …
Run Code Online (Sandbox Code Playgroud)

django oauth django-authentication jira-rest-api python-social-auth

5
推荐指数
1
解决办法
3369
查看次数

如何将自定义 Django 用户模型注册到管理页面?

我遵循了有关如何使用电子邮件而不是普通用户名来允许 Django 身份验证的教程,但是,他们没有提到如何在管理页面注册新的自定义用户模型!我是 Django 的真正初学者,所以我希望尽可能多地了解细节!到目前为止,这是我的代码:

经理.py

from django.contrib.auth.models import BaseUserManager

class CustomUserManager(BaseUserManager):

    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Email field is required')

        email = self.normalize_email(email)
        user = self.model(email=email, **kwargs)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)
        return self.create_user(email, password, **extra_fields)
Run Code Online (Sandbox Code Playgroud)

模型.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _

from .managers import CustomUserManager

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, …
Run Code Online (Sandbox Code Playgroud)

python django web-applications django-models django-authentication

5
推荐指数
1
解决办法
5420
查看次数

如何使用 url 参数重定向登录用户?

http://127.0.0.1:8000/在我的 Django 项目中,如果用户未登录,我试图将主页重定向到登录页面,但有一个已登录的用户我想http://127.0.0.1:8000/成为http://127.0.0.1:8000/username/

我尝试了不同的答案,但没有具体的答案:这是登录后的登录视图:

class LoginView(LoginView):
    template_name = 'login.html'

    def get_success_url(self):
        user=self.request.user.username
        return f'/{user}/'
Run Code Online (Sandbox Code Playgroud)

这是登录网址:

    path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'),
Run Code Online (Sandbox Code Playgroud)

这是主页视图:

class home(LoginRequiredMixin, ListView):
    model = Item
    template_name = 'app/home.html'
    context_object_name = 'items'
Run Code Online (Sandbox Code Playgroud)

这是应用程序网址:

    path('<str:username>/', home.as_view(), name='home'),
Run Code Online (Sandbox Code Playgroud)

我的问题:

http://127.0.0.1:8000/username/如果用户已登录,则如何重定向主页login page

python django django-urls django-views django-authentication

5
推荐指数
1
解决办法
401
查看次数

在Django中,如何使用特定的用户外键获取所有相关对象

我有这样的事情:

class Video(models.Model):
    user = models.ForeignKey(User, related_name='owner')
    ...
Run Code Online (Sandbox Code Playgroud)

并且我正在尝试通过执行以下操作来访问特定用户拥有的所有视频:

u = User.objects.get(pk=1)
u.video_set.all()
Run Code Online (Sandbox Code Playgroud)

我收到错误'用户对象没有属性video_set'

难道我做错了什么?

django django-models django-authentication django-related-manager

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

防止在allauth中创建社交帐户

是否有可能在某些情况下防止在allauth中创建帐户,最好使用pre_social_login信号?

django django-authentication django-allauth

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

Django 1.8 LookupError AUTH_USER_MODEL

我在我的app中使用了一个custon用户模型fowl.当我运行syncdb或者makemigrations还是migrate我收到了LookupError.请帮忙

settings.py我定义AUTH_USER_MODEL'fowl.User'

禽/ models.py

    from django.db import models
    from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
    from django.utils import timezone
    from django.core.mail import send_mail
    from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        ) …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-authentication django-1.8

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

没有名为'后端'的模块

我正在做这个简单的django教程 http://www.madewithtea.com/simple-todo-api-with-django-and-oauth2.html

这是我的settings.py文件

import os

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/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_q7lkj9bgdsdadsqx%kihv-tyf0ugn*vj8+6lbkds7ff5d&m1-b@837t'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',

    # TODO
    'provider',
    'provider.oauth2',

    'todo',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware', …
Run Code Online (Sandbox Code Playgroud)

python django django-authentication

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

如何在django中为新用户设置默认组?

如何为我创建的新用户设置默认组?我没有创建用户的自定义模型,我的django版本是1.11.

django django-models django-authentication django-users

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