Django 的 Python Social Auth 引发 Authforbidden 异常

标签 python django authentication google-signin

我将 Django 1.10 与 python 2.7 和 social-auth-app-django (1.2.0) 一起使用。它是 Python Social Auth 库的一部分。

我希望将登录限制为我公司的域 ID,因此我使用了库中的此设置。

SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS=['mycompany.in']

现在,如果您尝试按预期使用任何其他域登录,则会抛出错误。

我的目标是捕获此异常并向用户显示自定义页面。但是我这辈子都做不到。

如果我将 Debug 设置为 False,它会将用户重定向到我的

LOGIN_ERROR_URL='/'

页面但无法将我的自定义消息传递给用户

这是我setting.py的一部分

DEBUG = False

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

#social auth
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY= "9******6.apps.googleusercontent.com"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET="W*****x"
SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS=['mycompany.in']
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'upload_file'
LOGOUT_URL = 'logout'
LOGIN_ERROR_URL='logout

在我看来我有这段代码来处理异常

from social_django.middleware import SocialAuthExceptionMiddleware
from social_core.exceptions import AuthForbidden


    class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
      def process_exception(self, request, exception):
        print "exception occured"
        if hasattr(social_exceptions, 'AuthForbidden'):
          print "hello two"
          return HttpResponse("I'm a exception %s" % exception)
        else:
          print "other exception"
          raise exception

我什至尝试过

def process_template_response(self):
    print "response"'

def get_redirect_uri(request, exception):
    print "URL"

但是没有用。

我已经点击了这些链接 python-social-auth AuthCanceled exception

http://python-social-auth-docs.readthedocs.io/en/latest/configuration/django.html#exceptions-middleware

这是调试设置为 False 时的输出:

"AuthForbidden at /app/oauth/complete/google-oauth2/ Your credentials aren't allowed"

最佳答案

  1. 需要在 settings.py 中为 SOCIAL_AUTH_LOGIN_ERROR_URL 设置值
  2. 扩展 SocialAuthExceptionMiddleware 类并需要覆盖“get_message”方法
  3. 处理错误 URL 向用户显示消息。

例如

中间件.py

from social_django.middleware import SocialAuthExceptionMiddleware

class CustomSocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
    def get_message(self, request, exception):
       default_msg = super(CustomSocialAuthExceptionMiddleware).get_message(request, exception) # in case of display default message
       return "Custom messages text write here."

settings.py

SOCIAL_AUTH_LOGIN_ERROR_URL = '/error_page/'
MIDDLEWARE = [
'...',
'path.to.custom.middleware.CustomSocialAuthExceptionMiddleware',
]

URL.py

from django.conf.urls import url

from views import ErrorPage

urlpatterns = [
    url(r'^error_page/$', ErrorPage.as_view(), name="error-page"),
]

view.py

from django.views.generic.base import TemplateView

class ErrorPage(TemplateView):
    template_name = 'error.html'

error.html(模板)

....
   <body>
     {% if messages %}
        <ul class="messages">
           {% for message in messages %}
               <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }} </li>
        {% endfor %}
        </ul>
    {% endif %}
   </body>
....

如果你使用的是django消息框架。在不使用 django 消息框架的情况下,中间件将消息添加到 GET 参数中,您可以在错误页面上显示该消息。

关于Django 的 Python Social Auth 引发 Authforbidden 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44461471/

相关文章:

python - 计算 Twitter 上特定单词的结果数(API v1.1)

python - 使用 Python 和 Pandas 将基于另一列的列组合起来

python - 存储在新数据框中的 Pandas groupby

python - 您可能没有在您的 API 中包含相关模型,或者在此字段上错误地配置了 `lookup_field` 属性

security - 单个 SSL 证书,多个站点?

ios - 如何禁用 UITextField 以删除自定义编号

python - 内存游戏,检测两个图像相同的问题

python - call_command 参数是必需的

Django : Is it impossible to static tag into block tag?

azure - 验证 Oauth Bearer token ,Microsoft.Owin.Security.Jwt 4.x 中缺少 IIssuerSecurityTokenProvider