.NET Core 已经热了好一阵子,1.1版本发布后其可用性也越来越高,开源、组件化、跨平台、性能优秀、社区活跃等等标签再加上“微软爸爸”主推和大力支持,尽管现阶段对比.net framework还是比较“稚嫩”,但可以想象到它光明的前景。作为 .net 开发者你是否已经开始尝试将项目迁移到 .net core 上?这其中要解决的一个较大的问题就是如何让你的 .net core 和老 .net framework 站点实现身份验证兼容!

1、第一篇章

我们先来看看 .net core 中对 identity 的实现,在 Startup.cs 的 Configure 中配置 Cookie 认证的相关属性

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.UseCookieAuthentication(new CookieAuthenticationOptions
  4. {
  5. AuthenticationScheme = "test",
  6. CookieName = "MyCookie"
  7. });
  8. }

Controller

  1. public IActionResult Index()
  2. {
  3. return View();
  4. }
  5. public IActionResult Login()
  6. {
  7. return View();
  8. }
  9. [HttpPost]
  10. public async Task<IActionResult> Login(string name)
  11. {
  12. var identity = new ClaimsIdentity(
  13. new List<Claim>
  14. {
  15. new Claim(ClaimTypes.Name,name, ClaimValueTypes.String)
  16. },
  17. ClaimTypes.Authentication,
  18. ClaimTypes.Name,
  19. ClaimTypes.Role);
  20. var principal = new ClaimsPrincipal(identity);
  21. var properties = new AuthenticationProperties { IsPersistent = true };
  22. await HttpContext.Authentication.SignInAsync("test", principal, properties);
  23. return RedirectToAction("Index");
  24. }

login 视图

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>登录</title>
  5. </head>
  6. <body>
  7. <form asp-controller="Account" asp-action="Login" method="post">
  8. <input type="text" name="name" /><input type="submit" value="提交" />
  9. </form>
  10. </body>
  11. </html>

index 视图

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>欢迎您-@User.Identity.Name</title>
  5. </head>
  6. <body>
  7. @if (User.Identity.IsAuthenticated)
  8. {
  9. <p>登录成功!</p>
  10. }
  11. </body>
  12. </html>

下面是实现效果的截图:

ok,到此我们用 .net core 比较简单地实现了用户身份验证信息的保存和读取。

接着思考,如果我的 .net framework 项目想读取 .net core 项目保存的身份验证信息应该怎么做?

要让两个项目都接受同一个 Identity 至少需要三个条件:

  • CookieName 必须相同。
  • Cookie 的作用域名必须相同。
  • 两个项目的 Cookie 认证必须使用同一个 Ticket。

首先我们对 .net core 的 Cookie 认证添加 domain 属性和 ticket 属性

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\keyPath\"));
  4. var dataProtector = protectionProvider.CreateProtector("MyCookieAuthentication");
  5. var ticketFormat = new TicketDataFormat(dataProtector);
  6. app.UseCookieAuthentication(new CookieAuthenticationOptions
  7. {
  8. AuthenticationScheme = "test",
  9. CookieName = "MyCookie",
  10. CookieDomain = "localhost",
  11. TicketDataFormat = ticketFormat
  12. });
  13. }

此时我们在 .net core 项目中执行用户登录,程序会在我们指定的目录下生成 key.xml

我们打开文件看看程序帮我们记录了那些信息

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <key id="eb8b1b59-dbc5-4a28-97ad-2117a2e8f106" version="1">
  3. <creationDate>2016-12-04T08:27:27.8435415Z</creationDate>
  4. <activationDate>2016-12-04T08:27:27.8214603Z</activationDate>
  5. <expirationDate>2017-03-04T08:27:27.8214603Z</expirationDate>
  6. <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
  7. <descriptor>
  8. <encryption algorithm="AES_256_CBC" />
  9. <validation algorithm="HMACSHA256" />
  10. <masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection">
  11. <value>yHdMEYlEBzcwpx0bRZVIbcGJ45/GqRwFjMfq8PJ+k7ZWsNMic0EMBgP33FOq9MFKX0XE/a1plhDizbb92ErQYw==</value>
  12. </masterKey>
  13. </descriptor>
  14. </descriptor>
  15. </key>

ok,接下来我们开始配置 .net framework 项目,同样,在 Startup.cs 中配置 Cookie 认证的相关属性。

  1. public partial class Startup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\keyPath\"));
  6. var dataProtector = protectionProvider.CreateProtector("MyCookieAuthentication");
  7. var ticketFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));
  8. app.UseCookieAuthentication(new CookieAuthenticationOptions
  9. {
  10. AuthenticationType = "test",
  11. CookieName = "MyCookie",
  12. CookieDomain = "localhost",
  13. TicketDataFormat = ticketFormat
  14. });
  15. }
  16. }

view

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>.net framewor欢迎您-@User.Identity.Name</title>
  5. </head>
  6. <body>
  7. @if (User.Identity.IsAuthenticated)
  8. {
  9. <p>.net framework登录成功!</p>
  10. }
  11. </body>
  12. </html>

写法和 .net core 基本上是一致的,我们来看下能否成功获取用户名:

反之在 .net framework 中登录在 .net core 中获取身份验证信息的方法是一样的,这里就不重复写了。

然而,到此为止事情就圆满解决了吗?很遗憾,麻烦才刚刚开始!


2、第二篇章

如果你的子项目不多,也不复杂的情况下,新增一个 .net core 站点,然后适当修改以前的 .net framework 站点,上述实例确实能够满足需求。可是如果你的子站点足够多,或者项目太过复杂,牵扯到的业务过于庞大或重要,这种情况下我们通常是不愿意动老项目的。或者说我们没有办法将所有的项目都进行更改,然后和新增的 .net core 站点同时上线,如果这么做了,那么更新周期会拉的很长不说,测试和更新之后的维护阶段压力都会很大。所以我们必须要寻找到一种方案,让 .net core 的身份验证机制完全迎合 .net framwork。

因为 .net framework 的 cookie 是对称加密,而 .net core 是非对称加密,所以要在 .net core 中动手的话必须要对 .net core 默认的加密和解密操作进行拦截,如果可行的话最好的方案应该是将 .net framework 的 FormsAuthentication 类移植到 .net core 中。但是用 reflector 看了下,牵扯到的代码太多,剪不断理还乱,github 找到其开源地址:https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs ,瞎忙活了一阵之后终于感慨:臣妾做不到(>﹏< )。

不过幸好有领路人,参考这篇博文:http://www.cnblogs.com/cmt/p/5940796.html

Cookie 认证的相关属性

  1. app.UseCookieAuthentication(new CookieAuthenticationOptions
  2. {
  3. AuthenticationScheme = "test",
  4. CookieName = "MyCookie",
  5. CookieDomain = "localhost",
  6. TicketDataFormat = new FormsAuthTicketDataFormat("")
  7. });

FormsAuthTicketDataFormat

  1. public class FormsAuthTicketDataFormat : ISecureDataFormat<AuthenticationTicket>
  2. {
  3. private string _authenticationScheme;
  4. public FormsAuthTicketDataFormat(string authenticationScheme)
  5. {
  6. _authenticationScheme = authenticationScheme;
  7. }
  8. public AuthenticationTicket Unprotect(string protectedText, string purpose)
  9. {
  10. var formsAuthTicket = GetFormsAuthTicket(protectedText);
  11. var name = formsAuthTicket.Name;
  12. DateTime issueDate = formsAuthTicket.IssueDate;
  13. DateTime expiration = formsAuthTicket.Expiration;
  14. var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "Basic");
  15. var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
  16. var authProperties = new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties
  17. {
  18. IssuedUtc = issueDate,
  19. ExpiresUtc = expiration
  20. };
  21. var ticket = new AuthenticationTicket(claimsPrincipal, authProperties, _authenticationScheme);
  22. return ticket;
  23. }
  24. FormsAuthTicket GetFormsAuthTicket(string cookie)
  25. {
  26. return DecryptCookie(cookie).Result;
  27. }
  28. async Task<FormsAuthTicket> DecryptCookie(string cookie)
  29. {
  30. HttpClient _httpClient = new HttpClient();
  31. var response = await _httpClient.GetAsync("http://192.168.190.134/user/getMyTicket?cookie={cookie}");
  32. response.EnsureSuccessStatusCode();
  33. return await response.Content.ReadAsAsync<FormsAuthTicket>();
  34. }
  35. }

FormsAuthTicket

  1. public class FormsAuthTicket
  2. {
  3. public DateTime Expiration { get; set; }
  4. public DateTime IssueDate { get; set; }
  5. public string Name { get; set; }
  6. }

以上实现了对 cookie 的解密拦截,然后通过 webapi 从 .net framework 获取 ticket

  1. [Route("getMyTicket")]
  2. public IHttpActionResult GetMyTicket(string cookie)
  3. {
  4. var formsAuthTicket = FormsAuthentication.Decrypt(cookie);
  5. return Ok(new { formsAuthTicket.Name, formsAuthTicket.IssueDate, formsAuthTicket.Expiration });
  6. }

有了 webapi 这条线,解密解决了,加密就更简单了,通过 webapi 获取加密后的 cookie,.net core 要做的只有一步,保存 cookie 就行了

  1. [HttpPost]
  2. public async Task<IActionResult> Login(string name)
  3. {
  4. HttpClient _httpClient = new HttpClient();
  5. var response = await _httpClient.GetAsync($"http://192.168.190.134/user/getMyCookie?name={name}");
  6. response.EnsureSuccessStatusCode();
  7. string cookieValue = (await response.Content.ReadAsStringAsync()).Trim('\"');
  8. CookieOptions options = new CookieOptions();
  9. options.Expires = DateTime.MaxValue;
  10. HttpContext.Response.Cookies.Append("MyCookie", cookieValue, options);
  11. return RedirectToAction("Index");
  12. }

webapi 获取 cookie

  1. [Route("getMyCookie")]
  2. public string GetMyCookie(string name)
  3. {
  4. FormsAuthentication.SetAuthCookie(name, false);
  5. return FormsAuthentication.GetAuthCookie(name, false).Value;
  6. }

其余代码不用做任何更改,ok,我们来测试一下

ok,登录成功,至此完成.net framework和.net core身份验证的兼容,哎,如果 .net core 的团队能多考虑一些这方面的兼容问题,哪怕是一个折中方案也能让开发者更有动力去做迁移。

雁过留声,阅过点赞哈~~~


我的公众号《捷义》

ASP.NET Core 和 ASP.NET Framework 共享 Identity 身份验证的更多相关文章

  1. ASP.NET Core和ASP.NET Framework共享Identity身份验证

    .NET Core 已经热了好一阵子,1.1版本发布后其可用性也越来越高,开源.组件化.跨平台.性能优秀.社区活跃等等标签再加上"微软爸爸"主推和大力支持,尽管现阶段对比.net ...

  2. ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统

    为什么使用 Jwt 最近,移动开发的劲头越来越足,学校搞的各种比赛都需要用手机 APP 来撑场面,所以,作为写后端的,很有必要改进一下以往的基于 Session 的身份认证方式了,理由如下: 移动端经 ...

  3. 在ASP.NET Core 2.0中使用Facebook进行身份验证

    已经很久没有更新自己的技术博客了,自从上个月末来到天津之后把家安顿好,这个月月初开始找工作,由于以前是做.NET开发的,所以找的还是.NET工作,但是天津这边大多还是针对to B(企业)进行定制开发的 ...

  4. 如何在ASP.NET Core中应用Entity Framework

    注:本文提到的代码示例下载地址> How to using Entity Framework DB first in ASP.NET Core 如何在ASP.NET Core中应用Entity ...

  5. 使用ASP.NET Core MVC 和 Entity Framework Core 开发一个CRUD(增删改查)的应用程序

    使用ASP.NET Core MVC 和 Entity Framework Core 开发一个CRUD(增删改查)的应用程序 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻 ...

  6. 在ASP.NET Core中实现一个Token base的身份认证

    注:本文提到的代码示例下载地址> How to achieve a bearer token authentication and authorization in ASP.NET Core 在 ...

  7. 比较ASP.NET和ASP.NET Core[经典 Asp.Net v和 Asp.Net Core (Asp.Net Core MVC)]

    ASP.NET Core是.与.Net Core FrameWork一起发布的ASP.NET 新版本,最初被称为ASP.NET vNext,有一系列的命名变化,ASP.NET 5.0,ASP.NET ...

  8. ASP.NET Core 简介 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core 简介 - ASP.NET Core 基础教程 - 简单教程,简单编程 ← ASP.NET Core 基础教程 ASP.NET Core Windows 环境配置 → A ...

  9. 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)

    上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...

随机推荐

  1. LeetCode题解之Keys and Rooms

    1.题目描述 2.问题分析 使用深度优先遍历 3.代码 bool canVisitAllRooms(vector<vector<int>>& rooms) { int ...

  2. MySQL【Delete误操作】数据恢复【转】

    前言:      操作数据库时候难免会因为“大意”而误操作,需要快速恢复的话通过备份来恢复是不太可能的,因为需要还原和binlog差来恢复,等不了,很费时.这里先说明下因为Delete 操作的恢复方法 ...

  3. GitHub-分支管理03-多人合作【重点】

    参考博文:廖雪峰Git教程 1. 多人协作 当你从远程仓库克隆时,实际上Git自动把本地的master分支和远程的master分支对应起来了,并且,远程仓库的默认名称是origin. 要查看远程库的信 ...

  4. 不同主机的docker容器互相通信

    Docker启动时,会在宿主主机上创建一个名为docker0的虚拟网络接口,默认选择172.17.0.1/16,一个16位的子网掩码给容器提供了 65534个IP地址. docker0只是一个在绑定到 ...

  5. git pull request 流程

    git pull request 用于在 fork 官方 repo 到个人 github, 在本地修改后,向官方 repo 请求合并.在官方团队审查过代码后,就可以将自己所做的改动合并到官方 repo ...

  6. 用于文本分类的多层注意力模型(Hierachical Attention Nerworks)

    论文来源:Hierarchical Attention Networks for Document Classification 1.概述 文本分类时NLP应用中最基本的任务,从之前的机器学习到现在基 ...

  7. Spring事务嵌套

    学习一下Spring的事务嵌套:https://blog.csdn.net/zmx729618/article/details/77976793 重点句子: Juergen Hoeller 的话:   ...

  8. 最长回文(manacher模板)

    #include<iostream> #include<algorithm> #include<cstring> #include<cstdio> us ...

  9. spring mybatis整合

    mybatis和spring整合的配置方法有很多,核心都是一个矛盾:如何让spring管理mybatis为mapper生成的代理对象. 1.配置数据源 单独使用mybatis的时候数据源是在mybat ...

  10. 03 python 初学(字符格式化输出)

    #_author: lily #_date: 2018/12/16 name = input("your name: ") age = input("your age: ...