没有密码验证的Django [英] django authentication without a password
问题描述
我使用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)
我迟早见好就收落验证
的功能,但它附加一个后台
字段,这是需要登录。
I sooner just leave off the authenticate
function, but it attaches a backend
field, which is required by login.
推荐答案
这是简单的写这个自定义身份验证后端。如果创建yourapp / 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屋!