我正在尝试构建一个简单的 ASP.Net Core 2.2 Web 应用程序,允许 AzureAD 作为“外部提供商”。我在 Visual Studio 2019 中执行此操作。
作为一个 super 简单的演示项目,我首先创建一个使用 Azure AD 作为登录提供程序的新项目:
- 选择 ASP.NET Core Web 应用程序
- 选择 Web 应用程序(模型- View - Controller )
- 将身份验证更改为“工作或学校帐户”。它自动填写了我的域名(因为我登录了VS)
这将创建一个 Web 应用程序,设置为在所有页面上强制执行用户身份验证。当我运行该应用程序时,它会转到 Azure AD 并让我登录,然后再导航到 /home
页面。
回想一下,我说过我想将 Azure AD 添加为外部提供商。所以我在 Startup.cs 中找到了这一行:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
我删除了默认的身份验证方案以防止自动登录,如下所示:
services.AddAuthentication()
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
现在,当我运行该应用程序时,它会导航到登录
页面,并提供一个 azure 大按钮,让我可以使用 Azure Active Directory 登录。但点击该按钮不会让我登录。
所以我搭建了身份页面,并在 ExternalLogin
GET 例程处设置了一个断点。果然,点击 azure 大按钮就可以找到那里。单步执行代码,我发现调用 _signInManager.GetExternalLoginInfoAsync()
返回 null。
我被困住了。显然,(未记录的)配置魔法没有正确设置某些内容来满足对 GetExternalLoginInfoAsync
的调用。
最佳答案
该场景是您使用 asp.net 身份并通过 Azure AD 登录作为外部身份提供商。
您应该设置IdentityConstants.ExternalScheme
作为Azure AD身份验证的登录架构,以便您可以通过 _signInManager.GetExternalLoginInfoAsync()
获取外部用户信息:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => {
options.SignInScheme= IdentityConstants.ExternalScheme;
//other config
});
然后您可以搭建asp.net身份并进行修改以满足您的要求,在任何页面中触发外部登录( OnPost
中的 ExternalLogin.cshtml.cs
函数),就像默认模板(“azure 大按钮”)一样。
关于c# - Azure AD 为 "external provider"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57541187/