承载认证与ASP.NET核心RC2 404,而不是403 [英] Bearer Authentication with ASP.NET Core RC2 404 instead of 403

查看:237
本文介绍了承载认证与ASP.NET核心RC2 404,而不是403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用承载认证与ASP.NET核心RC2。它正在与用户authenticad和有作用,但是当用户没有授权(authenticad,但不具有的角色)我得到一个404错误,而不是403的预期。

Startup.cs

 公共无效ConfigureServices(IServiceCollection服务)
    {        services.AddCors(选项=>
        {
            options.AddPolicy(CorsPolicy
                建设者=>
                {
                    建设者
                        .WithOrigins(*)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                }
            );
        });        services.AddIdentity< APPUSER,AppRole>()AddEntityFrameworkStores< AppIdentityDbContext,INT>();        services.AddAuthorization();        services.AddMvc(配置=> {
            VAR政策=新AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                。建立();
            config.Filters.Add(新AuthorizeFilter(政策));
        })AddJsonOptions(选项=>
            options.SerializerSettings.ContractResolver =新CamelCasePropertyNamesContractResolver()
        );
    }    //此方法被运行时调用。使用此方法来配置HTTP请求管道。
    公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment ENV,ILoggerFactory的LoggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection(记录));
        loggerFactory.AddDebug();        如果(env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        其他
        {
            app.UseExceptionHandler(/家/错误);
        }        app.UseStaticFiles();
        变种signingKey = GetSigningKey();        app.UseJwtBearerAuthentication(新JwtBearerOptions()
        {
            AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
            AutomaticAuthenticate = TRUE,
            AutomaticChallenge = TRUE,
            TokenValidationParameters =新TokenValidationParameters()
            {
                IssuerSigningKey = signingKey,
                ValidateIssuerSigningKey = TRUE,
                ValidateLifetime = TRUE,
                ValidAudience =MyAudience
                ValidIssuer =MyIssuer
            }
        });        app.UseCors(配置=>
        {
            config.AllowCredentials();
            config.AllowAnyOrigin();
            config.AllowAnyHeader();
            config.AllowAnyMethod();
        });        app.UseIdentity();        app.UseMvc(路线=>
        {
            routes.MapRoute(
                名称:默认,
                模板:{控制器= HOME} / {行动=指数} / {?ID});
        });
    }    公共静态SecurityKey GetSigningKey()
    {
        VAR plainTextSecurityKey =这是我的共享,不那么秘密,秘密!
        返回新SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
    }


解决方案

使用 app.UseIdentity()将新增 CookieAuthentication 您的应用程序,因此所有未经授权的请求重定向到 /帐号/登录

也许你还没有添加任何途径来处理这所以它给了你404。

来源:<一个href=\"https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/BuilderExtensions.cs\" rel=\"nofollow\">https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/BuilderExtensions.cs

I am trying to use Bearer Authentication with ASP.NET Core RC2. It is working with user authenticad and has the role, but when the user is not authorized (authenticad but dont have the role) I get a 404 error instead of 403 expected.

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));
    }

解决方案

Using app.UseIdentity() will add CookieAuthentication to your application and hence all unauthenticated requests will redirect to /Account/Login.

Probably you haven't added any routes to handle this so it gave you a 404.

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

这篇关于承载认证与ASP.NET核心RC2 404,而不是403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆