我试图将Azure Active Directory凭据从ASP.NET Core 2.0 Web App传递到ASP.NET Core 2.0 Web API,以便Web API可以根据用户的属性和权限做出反应。
不可否认的是,在不同场景和组合中有很多关于这些技术的教程,但由于最近它的发布,我一直无法找到专门针对Core 2.0的明确帮助,而且我避免过于投入在任何Core 1.x教程中,因为它似乎有一些突破性的变化(JWT,身份验证等)。我是Core的新手,所以我不知道是什么。
我的目标是确定如何根据微软的建议/标准(如果存在)来完成这项工作。我希望最大限度地降低复杂性,并利用为此生态系统设计的工具。
我在Azure Active Directory中注册了Web App和Web API。当我调试我的Web应用程序时,我需要通过我的工作/学校帐户登录Microsoft,这是按预期工作的。
这与我使用模板/向导开始创建的内容完全没有修改,但仅供参考:
在Web App中:
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();
}
}
控制器/ 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)
}
在Web 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();
}
}
在最终尝试“c#asp core get access token”并获得这个非常有用的博客作为结果#3时,我想不出有多少查询我投入到谷歌中: