通过身份验证访问 [Authorize] 控制器时出现 404

asp*_*yct 4 .net asp.net-core identityserver4

我正在尝试在 ASP.NET MVC Core 应用程序 (.NetCore 2) 上使用 IdentityServer4 实现身份验证和访问控制。虽然这不是我第一次实现后端,但这是第一次使用 .net,而且我正在为一些事情苦苦挣扎。

我已经按照https://identityserver4.readthedocs.io/en/release/quickstarts/1_client_credentials.html以及之前页面的说明进行操作。

我还添加了示例,IdentityController因为它们显示:

using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace leafserver.Controllers
{
    [Route("/api/identity")]
    [Authorize]
    public class IdentityController : Controller
    {
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的实现与他们的示例之间存在一些差异。据我所知:

  • 我使用本地网络地址 (192.168.1.x) 而不是 localhost
  • 他们使用的是“Web 应用程序”,而我使用的是“Web Api”
  • 他们似乎使用ControllerBase而不是Controller作为超类
  • 我不确定他们使用的 ASP.NET MVC 和我使用的 MVC 之间是否有区别(我使用的是核心,他们似乎没有,但通常它应该仍然有效......)

我注意到的是以下内容:

  • 只要我不放一个[Authorize],一切都好。我得到 200 OK 的预期结果
  • [Authorize]注释在那里,但我没有使用身份验证不记名令牌时,我被重定向到登录页面(这不起作用,因为这是一个 web api,但这是以后的问题)
  • [Authorize]注释在那里,并且我使用(我认为是)正确的身份验证令牌时,我会收到 404 响应。

我原本希望得到 401 响应。为什么我的路由不起作用,因为我使用的是身份验证令牌?

另外,我没有从服务器获取任何日志,这无济于事...

小智 6

对我来说,答案是像这样在我的控制器上设置 Authorize 属性

[Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme)]
Run Code Online (Sandbox Code Playgroud)

这在最低权限指向的文档中进行了概述。 https://identityserver4.readthedocs.io/en/release/topics/add_apis.html

如果我只有 [Authorize] 那么它会产生 404


asp*_*yct 5

好吧,我已经找到问题了。

在我的 中Startup.ConfigureServices,我修改了添加服务的顺序。

    // https://identityserver4.readthedocs.io/en/release/quickstarts/1_client_credentials.html
    services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetTestUsers()); // TODO Remove for PROD

    // This MUST stay below the AddIdentityServer, otherwise [Authorize] will cause 404s
    services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(o =>
            {
                o.Authority = "http://localhost:5000";
                o.RequireHttpsMetadata = false; // TODO Remove for PROD
                o.ApiName = "leaf_api";
            });
Run Code Online (Sandbox Code Playgroud)

如果您在身份服务器之前添加身份验证,那么您将收到 404。按照这个顺序,它工作得很好。

这是供参考的完整Startup.cs文件:

using leafserver.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace leaf_server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<LeafContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddMvcCore()
                    .AddAuthorization()
                    .AddJsonFormatters();

            // https://identityserver4.readthedocs.io/en/release/quickstarts/1_client_credentials.html
            services.AddIdentityServer()
                    .AddDeveloperSigningCredential()
                    .AddInMemoryApiResources(Config.GetApiResources())
                    .AddInMemoryClients(Config.GetClients())
                    .AddTestUsers(Config.GetTestUsers()); // TODO Remove for PROD

            // This MUST stay below the AddIdentityServer, otherwise [Authorize] will cause 404s
            services.AddAuthentication("Bearer")
                    .AddIdentityServerAuthentication(o =>
                    {
                        o.Authority = "http://localhost:5000";
                        o.RequireHttpsMetadata = false; // TODO Remove for PROD
                        o.ApiName = "leaf_api";
                    });

            // https://dotnetcoretutorials.com/2017/01/17/api-versioning-asp-net-core/
            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseStatusCodePages();
            }

            app.UseIdentityServer();
            app.UseAuthentication();

            app.UseMvc();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)