我遇到了一个类似的问题,一个只暴露在前门后面的 WebApp,这个 WebApp 必须调用一个自定义的下游 WebApi。
在我的 localhost 开发机器上运行的服务配置:
// AzureAdB2C
services
.AddMicrosoftIdentityWebAppAuthentication(
Configuration,
"AzureAdB2C", subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true)
.EnableTokenAcquisitionToCallDownstreamApi(p =>
{
p.RedirectUri = redUri; // NOT WORKING, WHY?
p.EnablePiiLogging = true;
},
[... an array with my needed scopes]
)
.AddInMemoryTokenCaches();
我尝试了 AddDownstreamWebApi,但没有成功,所以我只是使用 ITokenAcquisition 获取所需的令牌并将其添加到 HttpClient 以发出我的请求。
然后我需要 AzureAd/B2C 登录重定向到带有前门 url 的 uri:
https://example.org/signin-oidc 事情发生了。我是这样解决的:
首先,您必须将此 url 添加到您在 azure 门户中的应用注册中,非常重要的是区分大小写,它关心尾部斜杠,我怀疑有许多 url 指向同一个控制器,并且它们的顺序有一些影响,我只是删除了所有内容并保持最低限度。
然后在configure services方法中:
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true; // this saves the token for the downstream api
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
// Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State
// that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize
// parameters sent to the identity provider.
ctxt.ProtocolMessage.RedirectUri = "https://example.org/signin-oidc";
await Task.Yield();
}
};
});
重定向成功了,但我在受保护页面和 AzureB2C 登录之间进入了一个循环。
在成功登录并正确重定向到 signin-oidc 控制器(由 Identity.Web 包创建)后,我再次被正确重定向到启动所有这些授权的页面,但在那里它没有找到授权。所以我也添加/修改了这个:
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;
options.Secure = CookieSecurePolicy.Always;
});
有了这个授权工作,但我无法让令牌调用下游 API,在此重定向事情 ITokenAcquisition 工作之前,但现在当尝试获取令牌时它会引发异常。
所以在我的控制器/服务中获取我修改和使用的令牌:
var accessToken = await _contextAccessor.HttpContext
.GetTokenAsync(OpenIdConnectDefaults.AuthenticationScheme, "access_token");
所以现在我使用令牌将它添加到我的 HttpRequestMessage 中,如下所示:
request.Headers.Add("Authorization", $"Bearer {accessToken}");
我在 StackOverflow 和 microsoft docs 上生活了 3 天,我不确定这是否都是“推荐”的,但这对我有用。