How to remove the redirect from an ASP.NET Core we

2020-02-10 13:14发布

Following the answer on this question, I have added authorization on everything by default, using the following code:

public void ConfigureServices(IServiceCollection aServices)
{
  aServices.AddMvc(options =>
  {
     var lBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();

     var lFilter = new AuthorizeFilter(lBuilder.Build());
     options.Filters.Add(lFilter);
   });

   aServices.AddMvc();
}

public void Configure(IApplicationBuilder aApp, IHostingEnvironment aEnv, ILoggerFactory aLoggerFactory)
{
  aApp.UseCookieAuthentication(options =>
  {
    options.AuthenticationScheme = "Cookies";
    options.AutomaticAuthentication = true;
  });
}

However when someone tries to access something unauthorized, it returns a (what seems a default) redirect URL (http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F).

I want it to return a HTTP 401 only, instead of a redirect.

How can I do this in ASP.NET 5 for a WebAPI?

6条回答
beautiful°
2楼-- · 2020-02-10 13:24

By the url you get redirected to I assume you're using cookie authentication.

You should get the desired results by setting the LoginPath property of the CookieAuthenticationOptions to null or empty as described by one of the users.

app.UseCookieAuthentication(options =>
        {
            options.LoginPath = "";
        });

It was probably working back then but it's not working anymore (because of this change).

I've submitted a bug on GitHub for this.

I'll update the answer once it gets fixed.

查看更多
\"骚年 ilove
3楼-- · 2020-02-10 13:25

I had a similar problem. I solved this adding by manually the services.

ConfigureServices method:

    services.AddTransient<IUserStore<User>, UserStore<User, IdentityRole, ApplicationDbContext>>();   
    services.AddTransient<IPasswordHasher<User>, PasswordHasher<User>>();
    services.AddTransient<IUserValidator<User>, UserValidator<User>>();
    services.AddTransient<ILookupNormalizer, UpperInvariantLookupNormalizer>();
    services.AddTransient<IPasswordValidator<User>, PasswordValidator<User>>();
    services.AddTransient<IdentityErrorDescriber, IdentityErrorDescriber>();
    services.AddTransient<ILogger<UserManager<User>>, Logger<UserManager<User>>>();
    services.AddTransient<UserManager<User>>();

    services.AddMvcCore()
    .AddJsonFormatters()
    .AddAuthorization();


    services.AddCors(options=> {
    options.AddPolicy("AllowAllHeaders", (builder) => {
        builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders("WWW-Authenticate"); ;
    });
});


    services.AddAuthentication(options=> {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddIdentityServerAuthentication(options =>
    {
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;
        options.ApiName = "api1";
        options.ApiSecret = "secret";
    });

Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("AllowAllHeaders");
    app.UseAuthentication();
    app.UseMvc();

}

I am using aspnet core 2.0, IdentityServer 4 and aspnet identity.

查看更多
4楼-- · 2020-02-10 13:32

I had with this problem in an Angular2 + ASP.NET Core application. I managed to fix it in the following way:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {
    // ...
    config.Cookies.ApplicationCookie.AutomaticChallenge = false;
    // ...
});

If this is not working for you, you can try with the following method instead:

services.AddIdentity<ApplicationUser, IdentityRole>(config =>   {
    // ...
    config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
    {
       OnRedirectToLogin = ctx =>
       {
           if (ctx.Request.Path.StartsWithSegments("/api")) 
           {
               ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
               // added for .NET Core 1.0.1 and above (thanks to @Sean for the update)
               ctx.Response.WriteAsync("{\"error\": " + ctx.Response.StatusCode + "}");
           }
           else
           {
               ctx.Response.Redirect(ctx.RedirectUri);
           }
           return Task.FromResult(0);
       }
    };
    // ...
}

Update for Asp.Net Core 2.0

Cookie options are now configured in the following way:

services.ConfigureApplicationCookie(config =>
            {
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx => {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        return Task.FromResult(0);
                    }
                };
            });
查看更多
看我几分像从前
5楼-- · 2020-02-10 13:35

Setting LoginPath = "" or null no longer works on Version 1.1.0.0. So here's what I did:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            ExpireTimeSpan = TimeSpan.FromDays(150),
            AuthenticationScheme = options.Cookies.ApplicationCookie.AuthenticationScheme,
            Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync,
                OnRedirectToLogin = async (context) => context.Response.StatusCode = 401,
                OnRedirectToAccessDenied = async (context) => context.Response.StatusCode = 403
            },
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
        });
查看更多
▲ chillily
6楼-- · 2020-02-10 13:35

Be aware, you should not use the CookieAuthentication only if you want to use your own Authentication Mechanism for example bypassing the Identity provider which not the case for most of us.

The default Identity provider use the CookieAuthenticationOptions behind the scene, you can configure it like the below.

services.AddIdentity<ApplicationUser, IdentityRole>(o =>
 {
     o.Password.RequireDigit = false;
     o.Password.RequireUppercase = false;
     o.Password.RequireLowercase = false;
     o.Password.RequireNonAlphanumeric = false;
     o.User.RequireUniqueEmail = true;

     o.Cookies.ApplicationCookie.LoginPath = null; // <-----
 })
 .AddEntityFrameworkStores<ApplicationDbContext>()
 .AddDefaultTokenProviders(); 

Tested in version 1.0.0

查看更多
相关推荐>>
7楼-- · 2020-02-10 13:42

in case it helps, below is my answer - with dotnet 1.0.1

its based on Darkseal's answer except I had to add the line ctx.Response.WriteAsync() to stop the redirect to the default 401 URL (Account/Login)

        // Adds identity to the serviceCollection, so the applicationBuilder can UseIdentity
        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {                
            //note: this has no effect - 401 still redirects to /Account/Login!
            //options.Cookies.ApplicationCookie.LoginPath = null;

            options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
            {
                OnRedirectToLogin = ctx =>
                {
                    //for WebApi: prevent aspnet core redirecting to 'Account/Login' on a 401:
                    if (ctx.Request.Path.StartsWithSegments("/api"))
                    {
                        ctx.RedirectUri = null;
                        ctx.Response.WriteAsync("{\"error\": " + ctx.Response.StatusCode + "}");
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                    return Task.FromResult(0);
                }
            };
        })
            .AddDefaultTokenProviders();
    }
查看更多
登录 后发表回答