Warm tip: This article is reproduced from serverfault.com, please click

其他-如何从ASP.NET Core Webapi中删除重定向并返回HTTP 401?

(其他 - How to remove the redirect from an ASP.NET Core webapi and return HTTP 401?)

发布于 2015-09-30 09:53:31

在回答这个问题之后,默认情况下,我使用以下代码对所有内容添加了授权:

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

但是,当某人尝试访问未经授权的内容时,它会返回一个(似乎是默认值)重定向URL(http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F)。

我希望它仅返回HTTP 401,而不是重定向。

如何在ASP.NET 5中为WebAPI执行此操作?

Questioner
Geerten
Viewed
11
15.6k 2017-09-10 11:26:31

我在Angular2 + ASP.NET Core应用程序中遇到了这个问题。我设法通过以下方式对其进行了修复:

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

如果这对你不起作用,则可以尝试使用以下方法:

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

Asp.Net Core 2.0的更新

现在可以通过以下方式配置Cookie选项:

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