这里有新鲜出炉的精品教程,程序狗速度看过来!
ASP.NET 是. NET FrameWork 的一部分,是一项微软公司的技术,是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术,它可以在通过 HTTP 请求文档时再在 web 服务器上动态创建它们。 指 Active Server Pages(动态服务器页面) ,运行于 IIS(Internet Information Server 服务,是 Windows 开发的 Web 服务器)之中的程序 。
本篇文章主要介绍了详解 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);
来源: http://www.phperz.com/article/17/0813/337987.html