我有一个用于测试的现有小应用程序,它在Web App和API的Asp.Net Core 1.1中,使用Azure AD B2C进行身份验证。我正在尝试将其移至.Net Core 2.0,但我无法确定如何使其正常工作,我尝试使用GitHub Azure-Samples for Web App和API中的两个示例,但我在尝试时遇到了未经授权或500错误访问api,如果您有一个使用2.0从Web应用程序调用web api并受AD B2C保护的工作示例,将非常感谢。
编辑:我用来测试的示例是:Web App:WebApp-OpenIDConnect-DotNet core2.0 Web Api:B2C-WebApi core2.0,我更改了appsettings值以匹配我的b2c目录。
对于我的asp.net核心1.1测试应用程序,我使用与上面相同的示例,但是来自主分支,具有相同的appsettings值。
默认编辑2,在startup.cs我有这个:
services.AddAuthentication()
.AddJwtBearer(option => new JwtBearerOptions
{
Authority = string.Format("https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/",
Configuration["Authentication:AzureAd:Tenant"], Configuration["Authentication:AzureAd:Policy"]),
Audience = Configuration["Authentication:AzureAd:ClientId"],
Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
}
});
这给了我以下错误:
Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 GET http://localhost:44352/api/values/5 Microsoft.AspNetCore.Server.Kestrel:错误:连接ID“0HL89JHF4VBLM”,请求ID“0HL89JHF4VBLM:00000001”:应用程序抛出了未处理的异常。 System.InvalidOperationException:未指定authenticationScheme,并且未找到DefaultChallengeScheme。
如果修改了services.AddAuthentication那样的话
services.AddAuthentication(sharedOption =>
{
sharedOption.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
错误现在
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:无法验证令牌xxx。 Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException:IDX10500:签名验证失败。没有提供安全密钥来验证签名。 at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token,TokenValidationParameters validationParameters),位于Microsoft.AspNetCore.Authentication.JwtBearer的System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token,TokenValidationParameters validationParameters,SecurityToken和validatedToken)。 JwtBearerHandler.d__6.MoveNext()
我在样本上看到了一个解决此问题的拉取请求(Link),services.AddAuthentication必须更改为:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["Authentication:AzureAd:Tenant"]}/{Configuration["Authentication:AzureAd:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["Authentication:AzureAd:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
};
});
我得到了这个示例适用于Core 1.1和Core 2.0,请添加Oath身份验证,如下所示,
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAdB2C(options => Configuration.Bind("Authentication:AzureAdB2C", options))
您将在“AzureAdB2CAuthenticationBuilderExtensions”类中定义配置选项,该类位于azure b2c project内部
看起来您的令牌没有从Azure更新它,您是否能够从您的Web应用程序获取令牌?你可以验证你没有得到null
您是否在azure b2c租户网络应用程序上注册了api范围? “ApiScopes”:“https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read”
你必须在web api中设置范围并允许在网络应用上阅读,请点击link进行设置