Detailed explanation of ASP. NET and ASP. NET Core user authentication Cookie coexistence solution

  • 2021-09-12 00:56:29
  • OfStack

When you migrate your existing user login (Sign In) site from ASP. NET to ASP. NET Core, you will face such a problem-how can ASP. NET and ASP. NET Core users verify that Cookie coexists, and ASP. NET applications and ASP. NET Core applications use their own Cookie? Because ASP. NET uses FormsAuthentication, ASP. NET Core uses claims-based authentication, and their encryption algorithms are different.

Our solution is to generate two Cookie respectively and send them to the client after logging in successfully in ASP. NET Core.

The claims-based authentication-based validation Cookie that generates ASP. NET Core is relatively simple, and the sample code is as follows:


var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, loginName) }, "Basic");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await context.Authentication.SignInAsync(_cookieAuthOptions.AuthenticationScheme,
  claimsPrincipal,
  new AuthenticationProperties
  {
    IsPersistent = isPersistent,
    ExpiresUtc = DateTimeOffset.Now.Add(_cookieAuthOptions.ExpireTimeSpan)
  });

The FormsAuthentication-based validation Cookie that generates ASP. NET is slightly more cumbersome.

First, create an Web API site with ASP. NET, and generate Cookie based on FormsAuthentication. The sample code is as follows:


public IHttpActionResult GetAuthCookie(string loginName, bool isPersistent)
{
  var cookie = FormsAuthentication.GetAuthCookie(loginName, isPersistent);
  return Json(new { cookie.Name, cookie.Value, cookie.Expires });
}

Then write an Web API client in the ASP. NET Core login site to get Cookie. The sample code is as follows:


public class UserServiceAgent
{
  private static readonly HttpClient _httpClient = new HttpClient();
  public static async Task<Cookie> GetAuthCookie(string loginName, bool isPersistent)
  {
    var response = await _httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsAsync<Cookie>();
  }
}

Finally, the Cookie of ASP. NET FormsAuthentication is specifically sent to the client in the processing code after the successful login of the ASP. NET Core login site. The sample code is as follows:


var cookie = await _userServiceAgent.GetAuthCookie(loginName, isPersistent);
var options = new CookieOptions()
{
  Domain = _cookieAuthOptions.CookieDomain,
  HttpOnly = true
};
if (cookie.Expires > DateTime.Now)
{
  options.Expires = cookie.Expires;
}
context.Response.Cookies.Append(cookie.Name, cookie.Value, options);

Related articles: