文章出處

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

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()