Detailed description of the Solutions for coexistence of Cookie authentication between ASP. NET and ASP. NET Core users, corecookie
After you log on to an existing user (Sign In) site from ASP. NET to ASP. NET Core, you will face such a problem-How to Make ASP. NET and ASP.. NET Core users verify that cookies coexist, so that ASP. NET Applications and ASP.. NET Core applications use their respective cookies? ASP. NET uses FormsAuthentication, and ASP. NET Core uses claims-based authentication, and their encryption algorithms are different.
The solution is to generate two cookies after successful logon in ASP. NET Core and send them to the client at the same time.
It is relatively simple to generate a claims-based authentication Cookie for ASP. NET Core. 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)
});
Generating authentication cookies for ASP. NET Based on FormsAuthentication is a little effort-consuming.
First, use ASP. NET to create a Web API site and generate a 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, log on to the ASP. NET Core website and write a Web API client to obtain the 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, after successfully logging on to the ASP. NET Core site, the processing code specifically sends the ASP. NET FormsAuthentication Cookie to the client. 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);
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.