在 ASP.NET Core 2.0 从 Web App 到 Web API 中使用 Azure Active Directory 身份验证

Using Azure Active Directory authentication in ASP.NET Core 2.0 from Web App to Web API

我正在尝试将 Azure Active Directory 凭据从 ASP.NET Core 2.0 Web App 传递到 ASP.NET Core 2.0 Web API,以便 Web API 可以根据用户的属性和权限做出反应。

诚然,在各种场景和组合中有很多关于这些技术的教程,但我一直难以找到明确的帮助特别是 Core 2.0 由于到它最近发布的时间,我避免对任何核心 1.x 教程投入太多,因为在这方面似乎有一些重大变化(JWT、身份验证等)。我是 Core 的新手,所以我不知道什么是什么。

我的目标是根据 Microsoft 的 suggestions/standards(如果存在)确定应该如何完成此操作。我想尽量减少复杂性并利用专为该生态系统设计的工具。


我已经在我的 Azure Active Directory 中注册了 Web 应用程序和 Web API。当我调试我的 Web 应用程序时,我需要通过我的 work/school 帐户登录 Microsoft,并且按预期工作。

这是我使用 templates/wizards 开始创建的所有未修改的内容,但仅供参考:

在网络应用程序中:

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // (other unrelated stuff)

        app.UseAuthentication();

        // (other unrelated stuff)
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(options => Configuration.Bind("AzureAd", options))
        .AddCookie();

        services.AddMvc();
    }
}

Controllers/HomeController.cs

[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        // ****************************************************************
        // let's imagine I wanted to call the Web API right here, passing authentication
        // and whatnot... what should that look like according to this framework?
        // ****************************************************************

        return View();
    }

    // (other unrelated actions)
}

在网络中 API:

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // (other unrelated stuff)

        app.UseAuthentication();
        app.UseMvc();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

        services.AddMvc();
    }
}

我想不出我向 Google 提出了多少问题,直到最终尝试 "c# asp core get access token" 并获得这个非常有用的博客作为结果 #3:

https://blogs.msdn.microsoft.com/gianlucb/2017/10/04/access-an-azure-ad-secured-api-with-asp-net-core-2-0/