[英]Web Application and API AzureAD authentication flow ASP.NET Core
[英]Asp.net Core 2.1 Pass AzureAd Authentication Bearer to Web Api which uses [Authorize]
我有一个 asp.net core web api,它使用 AzureAd 注册的应用程序服务进行身份验证。
它的目的是充当 UI 前端的后端服务。
我已经使用邮递员、标头、JWT 授权等测试了安全功能,并且成功运行。
现在,我在 asp.net core 2.1 中创建了一个前端作为 MVC Web 应用程序。
我在前端使用 AzureAd 登录。
作为测试,我尝试了对后端 Web api 的 ajax 请求。
但是,我收到 401 Unauthorized 响应,因为我不知道如何在请求标头中传递 Authorization Bearer,我认为这是我的问题。
我的问题是这是如何完成的?
如何从 asp.net core web 应用程序对 asp.net core web api 进行身份验证?
如果可能的话,我想使用这样的简化方法。
和/或,有没有更好的方法?
谢谢你的帮助。
在阅读了有关中间件和 HttpClient 请求的信息后,我找到了自己对这个问题的答案。 如果有人发现自己在同一条船上,这就是我解决的方法。
像这样如下:
获取和存储令牌 这会出现在您的 startup.cs 中,您可以在其中为 AzureAd/OpenIdConnect 配置服务。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.