voo*_*ant 20 openid authentication django
我正在使用django的默认身份验证系统,但我已添加到OpenID库中,我可以通过OpenID对用户进行身份验证.我想要做的是登录,但似乎使用默认的django auth系统,我需要他们的密码来验证用户.有没有办法绕过这个而不实际使用他们的密码?
我想做这样的事......
user = ... # queried the user based on the OpenID response
user = authenticate(user) # function actually requires a username and password
login(user)
Run Code Online (Sandbox Code Playgroud)
我很快就离开了这个authenticate
函数,但是它附加了一个backend
登录所需的字段.
Wil*_*hes 22
为此编写自定义身份验证后端很简单.如果使用以下内容创建yourapp/auth_backend.py:
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
Run Code Online (Sandbox Code Playgroud)
然后添加到您的settings.py:
AUTHENTICATION_BACKENDS = (
# ... your other backends
'yourapp.auth_backend.PasswordlessAuthBackend',
)
Run Code Online (Sandbox Code Playgroud)
在您的视图中,您现在可以在没有密码的情况下调用authenticate:
user = authenticate(username=user.username)
login(request, user)
Run Code Online (Sandbox Code Playgroud)
这有点像黑客,但如果你不想重写一堆东西,请删除身份验证
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
Run Code Online (Sandbox Code Playgroud)
user将是您的User对象
小智 7
为了在没有密码的情况下进行身份验证,请在您的settings.py
:
AUTHENTICATION_BACKENDS = [
# auth_backend.py implementing Class YourAuth inside yourapp folder
'yourapp.auth_backend.YourAuth',
# Default authentication of Django
'django.contrib.auth.backends.ModelBackend',
]
Run Code Online (Sandbox Code Playgroud)
在你的auth_backend.py
:
注意:如果您的应用程序有自定义模型,则从以下位置导入
.models
CustomUser
from .models import User
from django.conf import settings
# requires to define two functions authenticate and get_user
class YourAuth:
def authenticate(self, request, username=None):
try:
user = User.objects.get(username=username)
return user
except User.DoesNotExist:
return None
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)
在自定义登录请求的视图中:
# Your Logic to login user
userName = authenticate(request, username=uid)
login(request, userName)
Run Code Online (Sandbox Code Playgroud)
如需进一步参考,请使用此处的 django 文档。
归档时间: |
|
查看次数: |
11481 次 |
最近记录: |