簡體   English   中英

Net Core 2.0-JWT承載不保護路由

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

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

作者明確指出,需要添加[Authorize]以保護端點,但是除非明確指定[AllowAnonymous],否則我想保護所有端點。 我閱讀了其他有關JWT Bearer的教程,它們看起來完全一樣,但是作者說默認情況下應該請求授權...

這是我的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();
    }
}

在文檔中找不到任何看起來不同的東西,所以我知道我必須更改...我可以在標頭中沒有令牌的情況下調用任何路由。 有人知道嗎?

您應該能夠使用以下過濾器:

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