gpt4 book ai didi

c# - 如何使用安全声明代表 AAD 用户调用 Web API?

转载 作者:行者123 更新时间:2023-12-03 02:50:23 30 4
gpt4 key购买 nike

因此,为了让您大致了解我想要实现的目标,我有一个网络应用程序使用 AAD 身份验证,因此用户需要登录到 Microsoft 组织帐户为了使用 Web 应用程序(针对 .NET Core)中实现的大多数 Controller 。Visual Studio 为此类 Web 应用程序设置提供了一个模板。这模板项目似乎获取了用户的身份作为“ClaimsIdentity”(System.Security.Claims.ClaimsIdentity),到目前为止这是可以的,只要因为用户已通过 AAD 身份验证。我还有一个 .NET Core Web API 解决方案,Web 应用程序需要代表该解决方案进行调用已登录的用户。因此,我有一个 Web 应用程序,它让用户登录到 AAD,然后是一个 Web API(其中Web 应用程序调用),其 Controller 端点需要 AAD 身份验证的请求。为此,我的理解是网络应用程序需要包含登录身份Microsoft(在本例中为安全提供商)在它向 API 发出的请求。然后,API 将能够查看用户声明并采取相应行动。

问题就出在这里。作为 header ,我相信我需要提供 Microsoft 发送的访问 token 到网络应用程序..但是我找不到这个 token 。我能从 User 或 User.Identity 中提取的只是声明。如何我可以代表这些声明调用单独的 API 吗?我需要完全忽略模板吗Microsoft 提供的并且只需调用/token 端点?我只想以正确的方式做到这一点:)

这是 Web 应用 Startup 类中的 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

这是我想代表登录的 AAD 调用外部 Web API 来获取所需数据:

public IActionResult Index()
{
var user = User.Identity as ClaimsIdentity;

var request = (HttpWebRequest)WebRequest.Create("http://localhost:4110/data");
request.Headers["Authorization"] = "bearer " + getAccessToken_using_user;

var response = (HttpWebResponse)request.GetResponse();

var dataString = new StreamReader(response.GetResponseStream()).ReadToEnd();

return View();
}

当然,我的目的是将“getAccessToken_using_user”替换为 Microsoft 据称为 Web 应用程序提供的访问 token ,如其 diagram 中所示。 .

最佳答案

您可以使用 MSAL 获取下游 API 的访问 token 。

https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/on-behalf-of#practical-usage-of-obo-in-an-aspnet--aspnet-core-application

这是代表流程的完整示例:

https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2/tree/master/2.%20Web%20API%20now%20calls%20Microsoft%20Graph

public static IServiceCollection AddProtectedApiCallsWebApis(this IServiceCollection services, IConfiguration configuration, IEnumerable<string> scopes)
{
...
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.Events.OnTokenValidated = async context =>
{
var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();
context.Success();

// Adds the token to the cache, and also handles the incremental consent and claim challenges
tokenAcquisition.AddAccountToCacheFromJwt(context, scopes);
await Task.FromResult(0);
};
});
return services;
}
private async Task GetTodoList(bool isAppStarting)
{
...
//
// Get an access token to call the To Do service.
//
AuthenticationResult result = null;
try
{
result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
.ExecuteAsync()
.ConfigureAwait(false);
}
...

// Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do list service.
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

// Call the To Do list service.
HttpResponseMessage response = await _httpClient.GetAsync(TodoListBaseAddress + "/api/todolist");
...
}

关于c# - 如何使用安全声明代表 AAD 用户调用 Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416104/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com