Anu*_*nth 3 python django oauth-2.0 google-oauth django-allauth
我已经使用django-allauth为我的 Web 应用程序实现了社交登录(provider-google)。我只想允许有限的域访问应用程序。以下是我对allauth的设置
设置.py
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SOCIALACCOUNT_ADAPTER = 'mbaweb.socialaccount_adapter.NoNewUsersAccountAdapter'
LOGIN_REDIRECT_URL = "/"
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
'hd': 'abc.com'
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过使用“hd”参数,我只能允许域为“abc.com”的帐户。它限制所有其他域帐户。
但我的要求是允许应用程序的域列表
例如:- allowed_domains = ['abc.com', 'xyz.co.in', 'pqr.com']
有没有办法实现这一目标?
谢谢你的帮助。
我使用的方法是编写一个在某些条件下SocialAccountAdapter返回 false的自定义is_open_for_signup。
在设置中,添加以下内容:
SOCIALACCOUNT_ADAPTER = 'myapp.auth.adapters.SocialAccountAdapter'
Run Code Online (Sandbox Code Playgroud)
显然,更改路径myapp.auth以适合您的代码。
在相应的adapters.py文件中,添加如下内容:
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
def email_domain(email):
"""Extracts the domain from an email address.
Warning: this is simplified and you may want a true email address parser.
"""
return email.split('@')[-1]
# Note: this would be better in settings.py
allowed_signup_domains = [
'abc.com',
'seconddomain.com',
'etcetc.com',
]
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request, sociallogin):
if email_domain(sociallogin.user.email) not in allowed_signup_domains:
return False
return super(SocialAccountAdapter, self).is_open_for_signup(request, sociallogin)
Run Code Online (Sandbox Code Playgroud)
该方法并不完美,但可以完成工作并给用户带来某种“优雅”的失败。