【问题标题】:Protected web calls when token is not valid令牌无效时受保护的网络调用
【发布时间】:2019-11-29 23:28:49
【问题描述】:

我使用 .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 上它运行良好)。

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

【问题讨论】:

  • 您是否记得将app.UseAuthorization() 添加到中间件管道?
  • @juunas 是的。我已经更新了我的帖子。
  • 只是一个更新,Microsoft.Identity.Web 现在是一个 NuGet 包。我们鼓励使用它来更新您的库并修复错误。 Microsoft.Identity.Web wiki

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


【解决方案1】:

您的中间件顺序错误。路由需要在身份验证和授权之前。

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

【讨论】:

    【解决方案2】:

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

    如果你想在 Microsoft.Identity.Web 中使用不同的方案名称,可以使用以下方法:

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

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2018-12-02
      • 2016-01-21
      • 2017-03-26
      • 2018-03-14
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多