我是django社会认证的新手。我正在使用social-auth-app-django
来验证Microsoft Azure AD用户。身份验证过程运行良好,用户对象在数据库中创建。但是request.user在视图中撤销null。
Settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
# 'social.apps.django_app.default',
]
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',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
],
},
},
]
AUTHENTICATION_BACKENDS = (
'social.backends.azuread.AzureADOAuth2',
)
#settings.py
SOCIAL_AUTH_PIPELINE = {
'pipeline.new_users_handler'
}
查看
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
context = {
'title':'Home Page',
'year':datetime.now().year,
'request': request,
'user': request.user,
}
context_instance = RequestContext(request,context)
return render(
request,
'index.html',context)
当我以管理员或使用admin创建的任何其他用户身份登录时,request.user工作正常。问题是通过社会认证进行身份验证。
答案 0 :(得分:1)
你不需要所有这些,使用简单的语法
def home(request):
context = {
'title':'Home Page',
'year':datetime.now().year,
'request': request,
'user': request.user,
}
return render(
request,
'index.html',context)
但request.user
将返回null,直到用户未登录
将此内容添加到您的MIDDLEWARE
'social_django.middleware.SocialAuthExceptionMiddleware',
将其添加到最后的模板上下文处理器
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect', # <--