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

首頁 > 編程 > .NET > 正文

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

2024-07-10 13:32:04
字體:
來源:轉載
供稿:網友

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到ASP.NET教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汝城县| 邯郸市| 柏乡县| 资溪县| 彝良县| 新昌县| 大洼县| 临安市| 克什克腾旗| 鄂托克前旗| 图们市| 左贡县| 特克斯县| 遂宁市| 昌吉市| 繁昌县| 晋城| 沂源县| 富顺县| 聂拉木县| 凌云县| 册亨县| 浦县| 青州市| 黔江区| 英德市| 桐乡市| 德保县| 长岛县| 罗定市| 竹北市| 深泽县| 登封市| 桐庐县| 米易县| 买车| 鹤壁市| 辽宁省| 安塞县| 漳州市| 汉中市|