New gesture for ASP. NET Core cross site login redirection

  • 2021-10-27 06:56:22
  • OfStack

Preface

As an. NET programmer, the first pain is that since the birth of ASP. NET until the latest ASP. NET Core, cross-site login redirection cannot be directly realized (for example, visit https://q.cnblogs.com and jump to https://passport.cnblogs.com for login), and only jump to the current site.

Take ASP. NET Core as an example CookieAuthenticationOptions.LoginPath You can only specify a path, not a full url with a host name. ASP. NET Core automatically adds the host name of the current request at redirection.


services.AddAuthentication()
.AddCookie(options =>
{
 options.LoginPath = "/account/signin";
});

The ReturnUrl query parameter also contains only the path, not the full url.

In order to understand the pain, the antidote we took in the era of ASP. NET either did not use the login jump mechanism of ASP. NET, or made two jumps through the special UserController. Login Action. In the era of ASP. NET Core, we changed the antidote of Middleware and made jumps in the special Middleware (which is also troublesome).

After reading the source code of ASP. NET Core Authenticaion yesterday, we found a new antidote-modification CookieAuthenticationEvents.OnRedirectToLogin Delegate implements cross-site login redirection.

Here is how to make the new antidote.

Add the following configuration code to AddCookie in Startup. ConfigureServices to redirect using the modified url:


services.AddAuthentication()
.AddCookie(options =>
{
 var originRedirectToLogin = options.Events.OnRedirectToLogin;
 options.Events.OnRedirectToLogin = context =>
 {
  return originRedirectToLogin(RebuildRedirectUri(context));
 };
});

The implementation code of RebuildRedirectUri is as follows:


private static RedirectContext<CookieAuthenticationOptions> RebuildRedirectUri(
 RedirectContext<CookieAuthenticationOptions> context)
{
 if (context.RedirectUri.StartsWith(ACCOUNT_SITE))
  return context;

 var originUri = new Uri(context.RedirectUri);
 var uriBuilder = new UriBuilder(ACCOUNT_SITE);
 uriBuilder.Path = originUri.AbsolutePath;
 var queryStrings = QueryHelpers.ParseQuery(originUri.Query);
 var returnUrlName = context.Options.ReturnUrlParameter;
 var returnUrl = originUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + queryStrings[returnUrlName];
 uriBuilder.Query = QueryString.Create(returnUrlName, returnUrl).ToString();
 context.RedirectUri = uriBuilder.ToString();
 return context;
}

The above 1 pile of codes is used to realize the conversion of url. For details, please refer to Bo Wen https://q.cnblogs.com/q/108087/

This long-standing pain is finally based on ASP. NET Core's powerful expansion and configuration capabilities are relatively elegantly eliminated.

Summarize


Related articles: