令牌无效时受保护的网络通话

时间:2019-11-29 23:28:49

标签: jwt azure-active-directory asp.net-web-api2 microsoft-identity-platform

我使用.NET Core 3

我已经从https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/aspnetcore3下载了Microsoft.Identity.Web

我使用Azure AD来访问受保护的Web API。最近,我切换到了发生此问题的Core 3.0(在2.2上运行正常)。

当前,当我尝试使用无效令牌调用We​​b 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();
    });
}

2 个答案:

答案 0 :(得分:1)

您的中间件顺序错误。路由需要在认证和授权之前进行。

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

答案 1 :(得分:0)

一个观察,我注意到您正在使用方案值AzureAD。当前,Microsoft.Identity.Web使用OpenIdConnectDefaults.AuthenticationScheme作为默认方案(其值为 OpenIdConnect )。

如果要对Microsoft.Identity.Web使用不同的方案名称,则可以使用以下方法:

   services.AddAuthentication("MyScheme")
     .AddSignIn(Configuration);