【发布时间】:2021-11-14 01:27:04
【问题描述】:
我有两个 webapi A 和 B。我从 A 向 B 发出请求。A 包含来自 identityserver4 的用户信息,我只需将令牌传递给请求标头。除了身份服务器令牌之外,A 还使用我注册 B 的 AAD(Azure Active Directory)。因此,我还从 A 中检查了我的 AAD,以便我可以从 Azure 检索令牌以发送给 B,这正是 B 可以信任的请求来自受信任的注册来源。正如您所了解的,从 A 我有两个令牌,一个用于检查登录用户,另一个用于检查已注册的应用程序。我的 A 启动类如下所示:
public void ConfigureServices(IServiceCollection services)
{
Config = services.ConfigureAuthConfig<AuthConfig>(Configuration.GetSection("AuthConfig"));
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<ICurrentUser, CurrentUser>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(//this coming with identityserver token and user info
idt =>
{
idt.Authority = "https://gnoauth.se:5005";
idt.ApiName = "globalnetworkApi";
idt.SaveToken = true;
idt.RequireHttpsMetadata = true;
}
);
所以这是我的 A httpclienthelper,我在其中设置我的客户端标头发送到 B,因为我已经从身份服务器获得令牌和用户,所以我在这里做的另一件事是将 B 权限、客户端 ID 和秘密发送到用于检索第二个令牌的 AAD:
var context = new HttpContextAccessor().HttpContext;
var accessTokenFromIdentityserver = await
context.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
var tokenfromAAD = result.AccessToken;
defaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("AAD_Authentication", tokenfromAAD);
从这里我实际上拥有了我需要的一切,包括令牌和所有声明。正如您在默认请求头中看到的那样,我只能发送一个令牌,但我想将两个令牌都发送给 B,我如何配置请求标头才能做到这一点?
所以这里是 B 启动
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("AAD_Authentication", opt =>
{
opt.Audience = Configuration["AAD:ResourceId"];
opt.Authority = $"{Configuration["AAD:InstanceId"]}{Configuration["AAD:TenantId"]}";
opt.RequireHttpsMetadata = true;
})
.AddJwtBearer("IDS4_Authentication",
idt =>
{
idt.Authority = "https://gnoauth.se:5005";
idt.Audience = "globalnetworkApi";
idt.SaveToken = true;
idt.RequireHttpsMetadata = true;
}
);
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("AAD_Authentication", "IDS4_Authentication")
.Build();
但我还设置了一个策略,以便我需要从我的一些控制器中授权登录用户和应用程序注册,像这样
[Authorize(AuthenticationSchemes = "AAD_Authentication,IDS4_Authentication", Policy = "MyPolicy")]
我一直面临的大问题是如何从 A 发送两个令牌以及如何设置身份验证方案以便 B 实际上获得两个不记名身份验证方案
请帮忙
【问题讨论】:
标签: c# authentication identityserver4 dotnet-httpclient bearer-token