我使用 .NET Core 3
我使用 Azure AD 访问受保护的 Web API。最近我已经切换到出现问题的 Core 3.0(在 2.2 上它运行良好)。
目前,当我尝试使用无效令牌调用 web api 时,我进入
JwtBearerMiddlewareDiagnostics类方法
private static async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context)
{
Debug.WriteLine($"99. Begin {nameof(OnAuthenticationFailedAsync)}");
// Place a breakpoint here and examine context.Exception
await s_onAuthenticationFailed(context).ConfigureAwait(false);
Debug.WriteLine($"99. End - {nameof(OnAuthenticationFailedAsync)}");
}
这是绝对正确的,因为令牌是无效的。但在那之后我的受保护控制器方法仍然调用(我通过添加带有 Bearer 和令牌的标头从邮递员调用它们)。这是我的控制器:
[Route("api/Points")]
[ApiController]
[Authorize(AuthenticationSchemes = "AzureAD")]
public class InstallationPointController : ControllerBase
{
...
}
在 Startup.cs 中设置 AD 授权:
services.AddProtectedWebApi(Configuration,subscribeToJwtBearerMiddlewareDiagnosticsEvents:true)
.AddProtectedApiCallsWebApis(Configuration, new []{ "user.read", "offline_access" }).AddInMemoryTokenCaches();
更新
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}