【问题标题】:Asp.net Core 2.1 Pass AzureAd Authentication Bearer to Web Api which uses [Authorize]Asp.net Core 2.1 将 AzureAd 身份验证承载传递给使用 [Authorize] 的 Web Api
【发布时间】:2020-06-21 11:42:29
【问题描述】:
我有一个使用 AzureAd 注册应用服务进行身份验证的 ASP.NET Core Web API。
其目的是充当 UI 前端的后端服务。
我已经使用邮递员、标头、JWT 授权等测试了安全功能,并且成功运行。
现在,我在 ASP.NET Core 2.1 中创建了一个前端作为 MVC Web 应用程序。
我在前端有 AzureAd 登录。
作为测试,我尝试了对后端 Web API 的 Ajax 请求。
但是,我收到 401 Unauthorized 响应,因为我不知道如何在请求标头中传递授权承载,我认为这是我的问题。
我的问题是这是怎么做到的?
如何从 ASP.NET Core Web 应用向 ASP.NET Core Web API 进行身份验证?
如果可能的话,我想使用这样的简化方法。
和/或,有没有更好的方法?
【问题讨论】:
标签:
c#
asp.net-core
asp.net-core-mvc
asp.net-core-webapi
【解决方案1】:
在阅读了关于中间件和 HttpClient 请求的信息后,我找到了自己的答案。
万一有人发现自己在同一条船上,我就是这样解决的。
- 捕获天蓝色“Bearer”令牌并将令牌服务器端存储为用户的身份声明。
- 创建一个方法来向 Web Api 发送 http 请求。
如下:
获取和存储令牌
这将在您为 AzureAd/OpenIdConnect 配置服务的 startup.cs 中进行。
builder.Services.Configure(configureOptions);
builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
builder.AddOpenIdConnect(o =>
{
//Additional config snipped
o.Events = new OpenIdConnectEvents
{
OnTokenValidated = async context =>
{
ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
if (identity != null)
{
identity.AddClaim(new Claim("access_token", context.SecurityToken.RawData));
}
System.Diagnostics.Debug.WriteLine(context.SecurityToken.RawData + "\n\n");
}
};
});
使用授权令牌发送所有 HTTP 请求的方法。
public async Task<IActionResult> AjaxAction(string url)
{
if (User.Claims == null) return null;
System.Security.Claims.Claim claim = User.Claims.SingleOrDefault(s => s.Type == "access_token");
if (claim == null) return null;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", claim.Value);
string url_e = System.Web.HttpUtility.UrlEncode(url);
HttpResponseMessage response = await httpClient.GetAsync(url);
// Here we ask the framework to dispose the response object a the end of the user resquest
HttpContext.Response.RegisterForDispose(response);
return new HttpResponseMessageResult(response);
}