c# - Azure AD 为 "external provider"?

标签 c# azure azure-active-directory asp.net-identity asp.net-core-2.0

我正在尝试构建一个简单的 ASP.Net Core 2.2 Web 应用程序,允许 AzureAD 作为“外部提供商”。我在 Visual Studio 2019 中执行此操作。

作为一个 super 简单的演示项目,我首先创建一个使用 Azure AD 作为登录提供程序的新项目:

  1. 选择 ASP.NET Core Web 应用程序
  2. 选择 Web 应用程序(模型- View - Controller )
  3. 将身份验证更改为“工作或学校帐户”。它自动填写了我的域名(因为我登录了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/

相关文章:

Azure 图形 API

c# - 如何从 Azure AD JWT 声明中获取用户的名字和名字?

Azure 函数 - 使用 Active Directory 交互式身份验证连接到 Azure SQL 数据库

C# 如何添加一个ListView ClickListener

c# - 在 Elasticsearch 和嵌套中传递和比较具有不同时区的日期时间值

.net 8 预览版 Linux 上托管的 Azure 应用服务无法启动,显然要求安装 8.0.0-rc

azure - 无法让 Azure 虚拟机为网站提供服务

c# - 在单个查询中从 CosmosDb 中获取多种类型的实体

c# - 将文件上传控件作为参数传递给方法

azure - 如何将遥测数据输入到 Windows 10 UWP 应用程序中?