This article mainly introduced the detailed ASP. NET core user authentication cookie coexistence solution, with a certain reference value, interested in small partners can refer to.
As you migrate your existing user login (sign in) site from ASP. NET core, you will face the question of how to make ASP. NET-core user authentication cookie coexist, so that the ASP. Do the core apps use their own cookies separately? Because ASP. Formsauthentication,asp.net Core uses the claims-based authentication, and their encryption algorithms are different.
The workaround we take is to generate 2 cookies and send them to the client after successful login in ASP.
The claims-based authentication-based authentication 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)
});
Generating ASP. FormsAuthentication-based authentication cookies is a little more cumbersome.
The first thing to do is to create a Web API site with ASP. FormsAuthentication to generate a cookie based on the sample code 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 a Web API client in the ASP. NET Core login site to get 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, an ASP. NET FormsAuthentication cookie is sent specifically to the client in the processing code after the successful login of the ASP. NET Core login site, with the sample code 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 the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.