Python 一个项目的 Django 多重身份验证后端,如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17064443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:20:27  来源:igfitidea点击:

Django Multiple Authentication Backend for one project, HOW?

pythondjangoauthenticationbackend

提问by Rai Muhammad Ehtisham

Need serious help here.

这里需要认真的帮助。

I have an application written in django/python and I have to extend it and include some other solution as an "app" in this application. For example my app to be integrated is named "my_new_app" Now there is a backend authentication written for the main application and i cannot use it. I have a mysql db to query from and the main app uses cassendra and redis mostly. So my question is, is there any way i can use a separate authentication backend for the new app "my_new_app" and run the both in the same domain? Question may not be that clear, i'll clarify if asked.

我有一个用 django/python 编写的应用程序,我必须扩展它并在此应用程序中包含一些其他解决方案作为“应用程序”。例如,我要集成的应用程序名为“my_new_app”,现在为主应用程序编写了一个后端身份验证,我无法使用它。我有一个 mysql 数据库可供查询,主应用程序主要使用 cassendra 和 redis。所以我的问题是,有什么方法可以为新应用程序“my_new_app”使用单独的身份验证后端并在同一域中运行两者?问题可能不是那么清楚,如果被问到我会澄清的。

采纳答案by janos

You canhave multiple authentication backends. Just set the AUTHENTICATION_BACKENDSin settings.pyof your Django project to list the backend implementations you want to use. For example I often use a combination of OpenID authentication and the standard Django authentication, like this in my settings.py:

可以有多个身份验证后端。只需设置Django 项目的AUTHENTICATION_BACKENDSinsettings.py即可列出您要使用的后端实现。例如,我经常使用 OpenID 身份验证和标准 Django 身份验证的组合,如下所示settings.py

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_openid_auth.auth.OpenIDBackend',
    )

In this example Django will first try to authenticate using django.contrib.auth.backends.ModelBackend, which is the default backend of Django. If that fails, then it moves on to the next backend, django_openid_auth.auth.OpenIDBackend.

在此示例中,Django 将首先尝试使用 进行身份验证django.contrib.auth.backends.ModelBackend,这是 Django 的默认后端。如果失败,则它会移动到下一个后端django_openid_auth.auth.OpenIDBackend.

Note that your custom backends must be at a path visible by Django. In this example I have to add django_openid_authto INSTALLED_APPS, otherwise Django won't be able to import it and use it as a backend.

请注意,您的自定义后端必须位于 Django 可见的路径上。在这个例子中,我必须添加django_openid_authINSTALLED_APPS,否则 Django 将无法导入它并将其用作后端。

Also read the relevant documentation, it's very nicely written, easy to understand: https://docs.djangoproject.com/en/dev/topics/auth/customizing/

还阅读了相关文档,写的很好,通俗易懂:https: //docs.djangoproject.com/en/dev/topics/auth/customizing/

回答by Edwin Lunando

I've been through this problem before. This is the code I used.

我以前遇到过这个问题。这是我使用的代码。

This is the authentication backend at the api/backend.py

这是 api/backend.py 中的身份验证后端

from django.contrib.auth.models import User


class EmailOrUsernameModelBackend(object):

    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
             kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                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

And this is my settings.py

这是我的 settings.py

AUTHENTICATION_BACKENDS = (
    'api.backend.EmailOrUsernameModelBackend',
    'django.contrib.auth.backends.ModelBackend',
)

Hope it helps. Please tell me if you're still in trouble. This code will enable you to use email to authenticate the default Django user even in Django admin.

希望能帮助到你。如果您仍然遇到麻烦,请告诉我。此代码将使您能够使用电子邮件对默认 Django 用户进行身份验证,即使在 Django 管理员中也是如此。

回答by Rai Muhammad Ehtisham

Using multiple backend authentications is as simple as pie. You just need to understand the workflow of Django apps.

使用多个后端身份验证就像馅饼一样简单。您只需要了解 Django 应用程序的工作流程。

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.Backend1',
    'django_openid_auth.auth.Backend2',
    )

For example you have the following two backends defined. Django will first go to the first backend and you just need to put some logic in that backend so that, if its not related to that backend it get forwarded to the other backend or returned without any results. In case of no results django will automatically shift the request from first backend to the second and if available third one. I spend a lot of time on this and found out that it was not that complex.

例如,您定义了以下两个后端。Django 将首先转到第一个后端,您只需要在该后端中放置一些逻辑,这样,如果它与该后端无关,它将被转发到另一个后端或返回而没有任何结果。如果没有结果,django 会自动将请求从第一个后端转移到第二个后端,如果可用,则将请求转移到第三个后端。我花了很多时间在这上面,发现它并没有那么复杂。

回答by Shubham Yadav

Using Multiple AUTHENTICATION BACKENDS is very easy, you just need to add this to settings.py

使用 Multiple AUTHENTICATION BACKENDS 非常简单,您只需要将其添加到 settings.py

AUTHENTICATION_BACKENDS = (
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GoogleOAuth',
    'social_core.backends.facebook.FacebookOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

and this may create a problem at signup page so add a login argument in your signup view in views.py file like this login(request, user, backend='django.contrib.auth.backends.ModelBackend')

这可能会在注册页面上产生问题,因此在 views.py 文件中的注册视图中添加一个登录参数,例如 login(request, user, backend='django.contrib.auth.backends.ModelBackend')

def signup_view(request):
    if request.method=='POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user=form.save()
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            return redirect('home')