使用ASP.NET Core RC2 404而不是403进行承载身份验证

时间:2016-05-20 20:53:19

标签: authentication asp.net-web-api asp.net-core .net-core-rc2

我正在尝试使用带有ASP.NET Core RC2的承载身份验证。它正在使用用户authenticad并具有该角色,但是当用户未被授权(authenticad但没有角色)时,我得到404错误而不是403错误。

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder
                        .WithOrigins("*")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                }
            );
        });

        services.AddIdentity<AppUser, AppRole>().AddEntityFrameworkStores<AppIdentityDbContext, int>();

        services.AddAuthorization();

        services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        }).AddJsonOptions(options => 
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
        );
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/home/error");
        }

        app.UseStaticFiles();


        var signingKey = GetSigningKey();

        app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = new TokenValidationParameters()
            {
                IssuerSigningKey = signingKey,
                ValidateIssuerSigningKey = true,
                ValidateLifetime = true,
                ValidAudience = "MyAudience",
                ValidIssuer = "MyIssuer"
            }
        });

        app.UseCors(config =>
        {
            config.AllowCredentials();
            config.AllowAnyOrigin();
            config.AllowAnyHeader();
            config.AllowAnyMethod();
        });

        app.UseIdentity();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    public static SecurityKey GetSigningKey()
    {
        var plainTextSecurityKey = "This is my shared, not so secret, secret!";
        return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
    }

2 个答案:

答案 0 :(得分:3)

使用app.UseIdentity()会将CookieAuthentication添加到您的应用中,因此所有未经身份验证的请求都会重定向到/Account/Login

可能你没有添加任何路线来处理这个问题所以它给了你一个404。

来源:https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/BuilderExtensions.cs

答案 1 :(得分:0)

请检查位置app.UseIdentity()还有MVC路由app.UseMvc()。authenicate代码应该低于app.useIdenetity()以及Mvc rotuing的上方。像这样:app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();
        app.UseIdentity();


        app.UseCors(builder =>
           builder.AllowAnyOrigin()
           .AllowAnyHeader()
           .AllowAnyMethod()
           );



        app.UseSwagger();
        app.UseSwaggerUi();

        ConfigureAuth(app);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "index");
        });