這篇文章給大家分享的是有關如何解決ASP.NET與ASP.NET Core用戶驗證Cookie并存的問題的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
在你將現有的用戶登錄(Sign In)站點從ASP.NET遷移至ASP.NET Core時,你將面臨這樣一個問題——如何讓ASP.NET與ASP.NET Core用戶驗證Cookie并存,讓ASP.NET應用與ASP.NET Core應用分別使用各自的Cookie?因為ASP.NET用的是FormsAuthentication,ASP.NET Core用的是claims-based authentication,而且它們的加密算法不一樣。
我們采取的解決方法是在ASP.NET Core中登錄成功后,分別生成2個Cookie,同時發送給客戶端。
生成ASP.NET Core的基于claims-based authentication的驗證Cookie比較簡單,示例代碼如下:
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)
});生成ASP.NET的基于FormsAuthentication的驗證Cookie稍微麻煩些。
首先要用ASP.NET創建一個Web API站點,基于FormsAuthentication生成Cookie,示例代碼如下:
public IHttpActionResult GetAuthCookie(string loginName, bool isPersistent)
{
var cookie = FormsAuthentication.GetAuthCookie(loginName, isPersistent);
return Json(new { cookie.Name, cookie.Value, cookie.Expires });
}然后在ASP.NET Core登錄站點中寫一個Web API客戶端獲取Cookie,示例代碼如下:
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>();
}
}最后在ASP.NET Core登錄站點的登錄成功后的處理代碼中專門向客戶端發送ASP.NET FormsAuthentication的Cookie,示例代碼如下:
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);感謝各位的閱讀!關于“如何解決ASP.NET與ASP.NET Core用戶驗證Cookie并存的問題”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。