ASP.NET Core Authorize属性不能与JWT一起使用

我想在ASP.Net Core中实现基于JWT的安全性。 现在我想要做的就是在Authorization标题中读取不记名令牌,并根据我的标准验证它们。 我不需要(也不想)包含ASP.Net Identity。 实际上,我尽量避免使用尽可能多的MVC添加的内容,除非我真的需要它们。

我创建了一个最小化的项目,它演示了这个问题。 要查看原始代码,只需查看编辑历史记录即可。 我希望此示例拒绝所有/ api /图标的请求,除非它们为Authorization HTTP标头提供了相应的承载令牌。 该示例实际上允许所有请求

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Routing;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System;
using Newtonsoft.Json.Serialization;

namespace JWTSecurity
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; set; }

        public Startup(IHostingEnvironment env)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath);
            Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddAuthentication();
            services.AddMvcCore().AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver());
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("supersecretkey")),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                }
            });
            app.UseMvc(routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"));
        }
    }
}

控制器/ IconsController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace JWTSecurity.Controllers
{
    [Route("api/[controller]")]
    public class IconsController : Controller
    {
        [Authorize]
        public IActionResult Get()
        {
            return Ok("Some content");
        }
    }
}

找到了!

主要问题在于这一行:

services.AddMvcCore().AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver());

我注意到,通过从AddMvcCore()切换到AddMvc(),授权突然开始工作! 在深入了解ASP.NET源代码之后,为了查看AddMvc()作用,我意识到我需要第二次调用IMvcBuilder.AddAuthorization()

services.AddMvcCore()
    .AddAuthorization() // Note - this is on the IMvcBuilder, not the service collection
    .AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver());

您也正在使用身份验证,并且它隐含地包含Cookie验证。 可能您使用身份验证方案登录,并导致身份验证成功。

如果不需要身份验证(如果您只需要jwt身份验证),则移除身份验证,否则为Authorize属性指定Bearer方案,如下所示:

[Authorize(ActiveAuthenticationSchemes = "Bearer")]

使用Json Web令牌向授权属性添加验证方案[授权(AuthenticationSchemes =“承载者”)]

链接地址: http://www.djcxy.com/p/22405.html

上一篇: ASP.NET Core Authorize attribute not working with JWT

下一篇: What kind of bearer authentication token is this?