简体   繁体   English

Net Core 2.0-JWT承载不保护路由

[英]Net Core 2.0 - JWT Bearer not protecting routes

I followed the tutorial to configure JWT with Identity on Net Core 2.0 : https://medium.com/@lugrugzo/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8 我按照教程在Net Core 2.0上为JWT配置了Identity: https : //medium.com/@lugrugzo/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8

Author clearly states that there is need to add [Authorize] to protect endpoints, but I want to protect all endpoint unless explicitly specified [AllowAnonymous]. 作者明确指出,需要添加[Authorize]以保护端点,但是除非明确指定[AllowAnonymous],否则我想保护所有端点。 I read other tutorials about JWT Bearer and they look exactly the same but authors saying that it should request authorization by default... 我阅读了其他有关JWT Bearer的教程,它们看起来完全一样,但是作者说默认情况下应该请求授权...

This is my Startup.cs 这是我的Startup.cs

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // ===== Add DbContext ======
            var connectionString = Configuration.GetConnectionString("dbContext");
            services.AddEntityFrameworkNpgsql().AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));

        // ===== Add Identity ========
        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // ===== Add JWT =====
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
        services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer = Configuration.GetSection("jwt")["issuer"],
                    ValidAudience = Configuration.GetSection("jwt")["audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("jwt")["key"])),
                    ClockSkew = TimeSpan.Zero // remove delay of token when expire
                };
            });

        services.AddMvc();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });

    }

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

            app.UseDeveloperExceptionPage();
        }


        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });

        app.UseAuthentication();
        app.UseMvc();

        dbContext.Database.EnsureCreated();
    }
}

Can't find anything in docs looking differently so I would know what I have to change... I can call any route without the token in headers. 在文档中找不到任何看起来不同的东西,所以我知道我必须更改...我可以在标头中没有令牌的情况下调用任何路由。 Has anyone an idea? 有人知道吗?

You should be able to use filters like this: 您应该能够使用以下过滤器:

using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
{...}
services.AddMvc(config =>
{
   var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
   config.Filters.Add(new AuthorizeFilter(policy));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM