Disable redirecting API URLs in the ASP.NET core

I have an ASP.NET Core site that uses cookie validation for most pages. For these pages, it is desirable that a default server response involving 302 redirection for an unauthorized client is desired. However, the site also accepts API requests; they use API keys and cannot use cookies.

Ideally, I would like to disable cookie processing for API URLs in general, but in the minimum case I need to make sure that if the API client is unauthorized, the server does not respond with 302 redirects.

+5
authentication cookies asp.net-core asp.net-identity-2
source share
2 answers

Replace the redirect event handler with the one that uses the default behavior only if the path is not an API. In Startup.ConfigureServices add the following:

 services.ConfigureApplicationCookie(options => { options.Events.OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, options.Events.OnRedirectToAccessDenied); options.Events.OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, options.Events.OnRedirectToLogin); }); 

Use this helper method to replace redirection methods:

 static Func<RedirectContext<CookieAuthenticationOptions>, Task> ReplaceRedirector(HttpStatusCode statusCode, Func<RedirectContext<CookieAuthenticationOptions>, Task> existingRedirector) => context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = (int)statusCode; return Task.CompletedTask; } return existingRedirector(context); }; 

In this case, the methods of the API controller can call Unauthorized() and Forbid() , without causing redirection.

Update: Above for ASP.NET Core 2. The code for ASP.NET Core 1 is different.

+10
source share

For .net core 2.x, here's the fix (based on Edward's answer):

 services.ConfigureApplicationCookie(options => { options.Events = new CookieAuthenticationEvents { OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, context => options.Events.RedirectToAccessDenied(context)), OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, context => options.Events.RedirectToLogin(context)) }; }); 

where is the ReplaceRedirector :

 Func<RedirectContext<CookieAuthenticationOptions>, Task> ReplaceRedirector(HttpStatusCode statusCode, Func<RedirectContext<CookieAuthenticationOptions>, Task> existingRedirector) => context => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = (int)statusCode; return Task.CompletedTask; } return existingRedirector(context); }; 
0
source share

All Articles