我按照以下官方步骤尝试了该场景“Web 应用程序在 Azure Ad B2C 中调用 Web API https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-web-api-dotnet“,唯一的区别是我正在使用ASP.NET核心。我正在使用 AuthorizationCode 来获取访问令牌,但它总是返回 id 令牌并且空访问令牌.
-
创建 Azure AD B2C 租户 https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-get-started.
-
注册一个网络 API https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-app-registration#register-a-web-api.
-
注册网络应用程序 https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-app-registration#register-a-web-application.
-
制定政策 https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-policies.
-
授予 Web 应用程序使用 Web api 的权限 https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-access-tokens#granting-permissions-to-a-web-api.
My code:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme,
AutomaticChallenge = true,
ClientId = aadB2cSettings.ClientId,
MetadataAddress = $"{aadB2cSettings.Instance}{aadB2cSettings.Tenant}/v2.0/.well-known/openid-configuration?p={aadB2cSettings.B2cSignUpOrSignInPolicy}",
PostLogoutRedirectUri = aadB2cSettings.RedirectUrl,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async context =>
{
var authCode = context.TokenEndpointRequest.Code;
var b2cAuthority = $"{aadB2cSettings.Instance}tfp/{aadB2cSettings.Tenant}/{aadB2cSettings.B2cSignUpOrSignInPolicy}/v2.0/.well-known/openid-configuration";
var cca = new ConfidentialClientApplication(
aadB2cSettings.ClientId,
b2cAuthority,
aadB2cSettings.RedirectUrl,
new ClientCredential(aadB2cSettings.ClientSecret),
new TokenCache(),
null);
try
{
var authResult = await cca.AcquireTokenByAuthorizationCodeAsync(authCode, new[] { "https://hulab2c.onmicrosoft.com/b2cdemo/all" });
context.HandleCodeRedemption(authResult.AccessToken, authResult.IdToken);
}
catch (Exception ex)
{
throw ex;
}
}
},
使用fiddler捕获请求,是:
POST
https://login.microsoftonline.com/hulab2c.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_signuporsignin https://login.microsoftonline.com/hulab2c.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_signuporsigninHTTP/1.1
请求正文:
client_id=1ff91f47-08ee-4973-83f4-379ad7e0679c&client_info=1&client_secret=......&scope=https%3A%2F%2Fhulab2c.onmicrosoft.com%2Fb2cdemo%2Fall+offline_access+openid+profile&grant_type=authorization_code&code=...... ..&redirect_uri=https%3A%2F%2Flocalhost%3A44383%2F
Return:
{"id_token":"......","token_type":"承载","not_before":1494494423,"client_info":"......","scope":""}
所以只有 id 令牌,没有访问令牌。但我们应该在这里获取访问令牌,对吗?