【问题标题】:ASP.NET Core 3 API Ignores Authorize Attribute with BearertokenASP.NET Core 3 API 使用 Bearertoken 忽略授权属性
【发布时间】:2019-09-10 13:17:52
【问题描述】:

我正在开发一个 ASP.NET Core Web API。我正在使用最新版本 3.0.0-preview4.19216.2。

我的问题是,我的 API-Controller 忽略了 Authorize-Attribute 但在另一个控制器上该属性工作正常。

    [Route("api/[controller]")]
    [ApiController]
    [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]
    public class SuppliersController : ControllerBase
    {

        [HttpGet("GetAll")]
        public IActionResult GetAll()
        {
            var companyId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value); // throws nullreference exception

            return Ok();
        }
    }

但在另一个控制器上,我有类似的东西,但该属性按预期工作

    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UsersController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            var test = User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value;
        }

    }

在用户控制器中一切正常。

我也在没有

的 SupplierController 中尝试过

身份验证方案

但没有什么不同。

这是我在 Startup.cs 中的 AddAuthentication

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    },
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine(context);

                        return Task.CompletedTask;
                    },
                    OnMessageReceived = context =>
                    {
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

这是我完整的startup.cs

    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)
        {

            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            AuthenticationService.ConfigureSchoolProjectAuthentication(services, appSettingsSection);
            DependencyInjectionService.Inject(services);

            services.AddMvcCore()
                .AddNewtonsoftJson();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        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.UseAuthorization();
            app.UseAuthentication();

            app.UseRouting();
            app.UseEndpoints(routes =>
            {
                routes.MapControllers();
            });
        }
    }

奇怪的是,当我的 SupplierController 被调用时,我的授权逻辑没有被调用(使用调试器检查它),而当我调用我的 UserController 时,逻辑被执行。

我认为这就是声明无效的原因。但是为什么控制器有授权属性的时候逻辑不调用呢?

我的身份验证似乎无法完全正常工作,因为我只需在 Postman 中不使用身份验证即可访问我的所有控制器。我在这里做错了什么?

【问题讨论】:

    标签: c# asp.net .net asp.net-web-api asp.net-core


    【解决方案1】:

    好的,我在这篇博文中找到了答案 ASP.NET Core updates in .NET Core 3.0 Preview 4

    我必须从

    更改我的身份验证注册顺序
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
            app.UseHttpsRedirection();
            app.UseAuthorization();
            app.UseAuthentication();
    
            app.UseRouting();
            app.UseEndpoints(routes =>
            {
                routes.MapControllers();
            });
        }
    

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
            app.UseRouting();
    
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();
    
            app.UseEndpoints(routes =>
            {
                routes.MapControllers();
            });
        }
    

    所以这解决了我的问题。

    【讨论】:

    • 还有一个问题。你应该切换: app.UseAuthentication(); app.UseAuthorization();因为首先它应该进行身份验证,然后获得授权。否则你总是得到一个 401 因为他在没有身份验证时无法授权
    • @Vampirasu 感谢回复。我将对其进行测试,因为目前一切正常。但再次感谢提示!
    • @Vampirasu 抱歉回复晚了。我纠正错误。感谢您指出!
    猜你喜欢
    • 2014-10-16
    • 2021-01-12
    • 2018-08-19
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2011-09-03
    • 2020-02-10
    • 2020-09-27
    相关资源
    最近更新 更多