services.AddIdentity 导致我的控制器端点响应 404

services.AddIdentity causes my controller's endpoint to respond with 404

我在向我的应用程序添加新的 Bearer 身份验证方面遇到一些困难,我无法弄清楚,我需要的一段代码导致我的端点 return 出现 404 错误,然而当移除后我能够成功地到达端点而没有 404 错误,见下文。

首先,我的应用程序既充当身份服务器,又充当接受承载令牌的 API。

        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = "https://www.example.com/";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
            });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiScope", policy =>
            {
                policy.RequireAuthenticatedUser();
                policy.RequireClaim("scope", "openid");
            });
        });

        // THIS IS THE CODE CAUSING THE 404 ERROR
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<DevContext>();

从上面可以看出,如果我尝试到达使用 [Authorize] 修饰的控制器端点,则会收到 404 响应。如果我注释掉最后几行(请参阅代码中的注释),那么我就可以成功到达终点。

为什么我会收到 404 错误?我认为这一定是因为 .AddIdentity 正在覆盖 Bearer 身份验证并且因为我的控制器装饰有 [Authorize] 我无法访问它?

我的应用程序不能同时作为 API 和 Identity Server 吗?


这是我在取消注释有问题的代码(404 响应)时在输出日志中看到的内容:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/api
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Information: AuthenticationScheme: Identity.Application was challenged.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 13.422ms 302 
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/Account/Login?ReturnUrl=%2Fapi
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 2.0776ms 404 

有问题的代码被注释掉(成功回复)时看到的是这样的:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/api
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: Successfully validated the token.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization was successful.

Kirk Larkin 的评论帮助解决了这个问题,总结一下:

  1. AddIdentity 必须放在对 AddAuthentication
  2. 的调用之上
  3. 我的控制器必须用 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
  4. 装饰