How to remove the redirect from an ASP.NET Core webapi and return HTTP 401?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.

Method 3

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

Method 4

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.

Method 5

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

Method 6

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

Method 7

Use this code in Startup :

services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = $"/Account/Login";
                options.LogoutPath = $"/Account/Logout";
                options.AccessDeniedPath = $"/Account/AccessDenied";
                options.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = (ctx) =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                            ctx.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    },
                    OnRedirectToAccessDenied = (ctx) =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                            ctx.Response.StatusCode = 403;
                        return Task.CompletedTask;
                    }
                };
            });


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x