Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-core c# cookie-authentication

How to make cookie auth scheme generate relative login url instead of absolute one?

发布于 2020-03-27 10:15:52

When ASP.NET Core authentication scheme redirects to Login Page it sends absolute url to the browser.

Is is possible to make this url relative?

Questioner
Pavel Voronin
Viewed
195
Kirk Larkin 2019-07-03 22:39

You can handle the OnRedirectToLogin event to provide your own logic for the redirection process. Here's an example implementation:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o =>
    {
        o.Events = new CookieAuthenticationEvents
        {
            OnRedirectToLogin = ctx =>
            {
               var relativeRedirectUri = new Uri(ctx.RedirectUri).PathAndQuery;

               context.Response.Headers["Location"] = relativeRedirectUri;
               context.Response.StatusCode = 401;

               return Task.CompletedTask;
           }
       };
   });

The ctx.RedirectUri property passed in is absolute, so the code above makes a relative copy and uses that instead.

The default implementation that this replaces is a little more involved, as it supports both AJAX requests that return a 401 and non-AJAX requests that perform a redirect. If you need to support both, have a look at the source and modify it accordingly.