访问经过身份验证的[授权]控制器时获取404 [英] Getting a 404 when accessing an [Authorize] controller when authenticated

查看:25
本文介绍了访问经过身份验证的[授权]控制器时获取404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ASP.NET MVC核心应用程序(.NetCore2)上的标识服务器4实现身份验证和访问控制。虽然这不是我第一次实现后端,但这是我第一次使用.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 });
        }
    }
}

我的实现与他们的示例之间有一些不同。据我所知:

  • 我使用的是本地网络地址(192.168.1.x),而不是本地主机
  • 他们使用的是"Web应用程序",而我使用的是"Web Api"
  • 它们似乎使用ControllerBase而不是Controller作为超类
  • 我不确定他们使用的ASP.NET MVC和我使用的是否有区别(我使用的是core,他们似乎没有,但正常情况下它应该仍然可以工作...)

我注意到的是:

  • 只要我不放[Authorize],一切都好。我得到了200分,符合预期结果
  • 如果有[Authorize]注释,但我没有使用身份验证载体令牌,我将被重定向到登录页面(由于这是一个Web API,因此无法工作,但这是以后的问题)
  • 如果存在[Authorize]注释,并且我使用(我认为是)正确的身份验证令牌,我会得到404响应。

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

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

推荐答案

好了,我找到问题了。

在我的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";
            });
如果您在身份服务器之前添加身份验证,那么您将获得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();
        }
    }
}

这篇关于访问经过身份验证的[授权]控制器时获取404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆