国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

詳解ASP.NET與ASP.NET Core用戶驗證Cookie并存解決方案

2024-07-10 12:49:17
字體:
來源:轉載
供稿:網友

在你將現有的用戶登錄(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);

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南开区| 大同县| 大渡口区| 大港区| 苍梧县| 嘉荫县| 福州市| 泌阳县| 方正县| 宜川县| 井研县| 南江县| 武清区| 古浪县| 丹巴县| 龙井市| 昌宁县| 乌鲁木齐县| 荔波县| 三亚市| 龙南县| 米易县| 大埔区| 姜堰市| 宝丰县| 江门市| 樟树市| 莲花县| 虎林市| 财经| 河曲县| 长治县| 兴仁县| 远安县| 晋江市| 和林格尔县| 汉沽区| 新泰市| 祁东县| 鄯善县| 志丹县|