Azure 中的用户身份

User Identity in Azure

我开始关注 Microsoft Azure,以期在那里部署未来的 Web 应用程序。大多数应用程序都会有一些“用户身份”的概念,因此使用云的好处之一就是委托身份验证。

第一步是创建 Visual Studio 的开箱即用 MVC 应用程序(无身份验证)并部署它,这非常简单。 下一步是将身份验证分层到此应用程序上。我完全通过 Azure 门户完成了这项工作,没有更改任何代码。现在只使用 Azure AD。再一次,很好。 第三步是编写另一个测试平台。我使用了 Windows 身份验证,ASP.NET 核心 MVC Web 应用程序,并在控制器中添加了代码:

string User = HttpContext.User.Identity.Name;
if (String.IsNullOrEmpty(User)) User = "<unknown>";

ViewBag.UserName = User;
return View();

在视图中,添加了一些noddy razor 来显示名称。本地测试,没问题。上传到 Azure,什么都没有。既不是未经身份验证的应用程序(就 Azure 门户而言),也不是经过 Azure AD 身份验证的应用程序。

深入挖掘,我发现了 Nuget 包 Microsoft.Identity 和 Azure.Identity,它们看起来很有前途,但现在却令人困惑。我刚开始 2 天前。

有什么指点吗?

我正在寻找一个要部署到 Azure 的 c# asp.net 核心 Web 应用程序,并让该应用程序显示某种识别,即它知道最终用户是谁。所以,基本上,一些 C# 代码放在控制器中以替换我的非工作代码。

根据你写的,我明白了:

  • 您已设置 Azure 应用服务
  • 您已使用“Easy Auth”来利用 Azure Active Directory 身份验证
  • 您想在您的应用程序中访问有关经过身份验证的用户的信息

你应该看看“Work with user identities in Azure App Service authentication”。

Access user claims in app code For all language frameworks, App Service makes the claims in the incoming token (whether from an authenticated end user or a client application) available to your code by injecting them into the request headers. External requests aren't allowed to set these headers, so they are present only if set by App Service. Some example headers include:

  • X-MS-CLIENT-PRINCIPAL-NAME
  • X-MS-CLIENT-PRINCIPAL-ID

Code that is written in any language or framework can get the information that it needs from these headers.

专门针对ASP.NET核心,确实可以使用Microsoft.Identity.Web,如here所述。

From version 1.2.0, the same code for your web app written with Microsoft.Identity.Web will work seamlessly with our without EasyAuth. Your web app can sign-in users and possibly call web APIs or Microsoft Graph. Indeed, Microsoft.Identity.Web now detects that the app is hosted in App Services, and uses that authentication.

还有一个完整的example blog post,我认为对你来说关键的部分是:

<PackageReference Include="Microsoft.Identity.Web" Version="1.4.1" />

在Startup.cs中:

public void ConfigureServices(IServiceCollection services) {
    //...
    services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
    //...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    //...
    app.UseAuthentication();
    app.UseAuthorization();
    //...
}