Bearer Authentication with ASP.NET Core RC2 404 instead of 403
Asked Answered
Y

2

0

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));
    }
Yuriyuria answered 20/5, 2016 at 20:53 Comment(0)
I
3

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

Ingrowth answered 21/5, 2016 at 5:22 Comment(1)
Yes, it was some like this. I changed AutomaticChallenge = false from configs to app.UseIdentity()Yuriyuria
I
0

Please check position app.UseIdentity() also MVC routing app.UseMvc().authenicate code should be below of app.useIdenetity() and above of Mvc rotuing. like this: 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");
        });
Individualize answered 22/2, 2017 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.