没有密码的django身份验证 [英] django authentication without a password

查看:61
本文介绍了没有密码的django身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 django 中使用默认身份验证系统,但我添加了一个 OpenID 库,我可以在其中通过 OpenID 对用户进行身份验证.我想做的是让他们登录,但似乎使用默认的 django 身份验证系统,我需要他们的密码来验证用户身份.有没有办法在不实际使用他们的密码的情况下解决这个问题?

I'm using the default authentication system with django, but I've added on an OpenID library, where I can authenticate users via OpenID. What I'd like to do is log them in, but it seems using the default django auth system, I need their password to authenticate the user. Is there a way to get around this without actually using their password?

我想做这样的事情...

I'd like to do something like this...

user = ... # queried the user based on the OpenID response
user = authenticate(user) # function actually requires a username and password
login(user)

我很快就放弃了 authenticate 功能,但它附加了一个 backend 字段,这是登录所必需的.

I sooner just leave off the authenticate function, but it attaches a backend field, which is required by login.

推荐答案

为此编写自定义身份验证后端非常简单.如果您使用以下内容创建您的应用程序/auth_backend.py:

It's straightforward to write a custom authentication backend for this. If you create yourapp/auth_backend.py with the following contents:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class PasswordlessAuthBackend(ModelBackend):
    """Log in to Django without providing a password.

    """
    def authenticate(self, username=None):
        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

然后添加到您的 settings.py:

Then add to your settings.py:

AUTHENTICATION_BACKENDS = (
    # ... your other backends
    'yourapp.auth_backend.PasswordlessAuthBackend',
)

在您看来,您现在可以在没有密码的情况下调用身份验证:

In your view, you can now call authenticate without a password:

user = authenticate(username=user.username)
login(request, user)

这篇关于没有密码的django身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆