我需要服务到服务的身份验证。
我遵循了此文档Azure AD B2C s2s
到目前为止,一切看起来都很好,除了我不能以任何其他方式获取客户端服务的访问令牌,而不仅仅是显式地调用POST身份验证端点。
因此,我能够在代码中检索访问令牌,如下所示:
var bodyContent = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("client_secret", "xxx"),
new KeyValuePair<string, string>("scope", "https://xxx/.default")
};
var result = await _httpClient.PostAsync("auth_url", new FormUrlEncodedContent(bodyContent));
var accessToken = await result.Content.ReadFromJsonAsync<AccessTokenResponse>()
我试图实现的是使用以某种方式自动工作
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, Constants.AzureAdB2C)
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { builder.Configuration["MyScope"] })
.AddInMemoryTokenCaches();
然后获取这样的令牌:
string result = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
而不是像上面的例子那样手动执行。
但无论我想做什么,我仍然会得到没有帐户或登录提示被传递给呼叫
更新02/11/2022
看起来你只是使用了错误的方法来请求授权码
当您希望(守护程序或应用程序(服务向另一个服务进行身份验证时:
不要使用GetAccessTokenForUserAsync(); // Wrong, it uses the current logged in user for the request
请使用GetAccessTokenForAppAsync() // Correct, it request a code via client_credentials flow
简短回答:您将范围传递给.EnableTokenAcquisitionToCallDownstreamApi((,而不是附加了单独应用程序注册的AzureAD OpenIdConnect配置。
答案很长:
";OAuth 2.0客户端凭据授予流允许应用程序(机密客户端(在调用web资源(如REST API(时使用其自己的凭据,而不是模拟用户进行身份验证">[Microsoft Docs]
此流不向发起请求的用户授权,而是使用自己的凭据。
因此,您需要在AzureAD B2C中注册3个应用程序。
-
[1]用户登录的前端应用程序注册
-
[2]您将用于生成授权码和授权范围
-
[3]您尝试呼叫的服务的应用程序注册。
这样,您就可以在前端的AppSettings.json中添加一个新的部分(例如,将其命名为"downstreamApi"(,其中包含客户端机密、范围和一些默认的OIDC设置,如Authority,然后您可以简单地调用
services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.EnableTokenAquisitionToCallDownstreamApi()
.AddDownStreamWebApi("MyAPI", Configuration.GetSection("downStreamApi");