如何使ASP.NETCore和ASP.NETFramework共享身份验证
创始人
2024-11-28 06:40:39
0次

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

1、第一篇章

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
    AuthenticationScheme = "test",
    CookieName = "MyCookie"
  });
}

Controller

public IActionResult Index()
{
  return View();
}

public IActionResult Login()
{
  return View();
}

[HttpPost]
public async Task Login(string name)
{
  var identity = new ClaimsIdentity(
          new List
          {
          new Claim(ClaimTypes.Name,name, ClaimValueTypes.String)
          },
          ClaimTypes.Authentication,
          ClaimTypes.Name,
          ClaimTypes.Role);
  var principal = new ClaimsPrincipal(identity);
  var properties = new AuthenticationProperties { IsPersistent = true };

  await HttpContext.Authentication.SignInAsync("test", principal, properties);

  return RedirectToAction("Index");
}

login 视图




  登录


  
    
  

index 视图




 欢迎您-@User.Identity.Name


  @if (User.Identity.IsAuthenticated)
  {
    

登录成功!

  }

下面是实现效果的截图:

如何使ASP.NETCore和ASP.NETFramework共享身份验证

如何使ASP.NETCore和ASP.NETFramework共享身份验证

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

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

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

  • CookieName必须相同。

  • Cookie的作用域名必须相同。

  • 两个项目的Cookie认证必须使用同一个Ticket。

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\keyPath\"));
  var dataProtector = protectionProvider.CreateProtector("MyCookieAuthentication");
  var ticketFormat = new TicketDataFormat(dataProtector);

  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
    AuthenticationScheme = "test",
    CookieName = "MyCookie",
    CookieDomain = "localhost",
    TicketDataFormat = ticketFormat
  });
}

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

如何使ASP.NETCore和ASP.NETFramework共享身份验证

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



 2016-12-04T08:27:27.8435415Z
 2016-12-04T08:27:27.8214603Z
 2017-03-04T08:27:27.8214603Z
 
  
   
   
   
    yHdMEYlEBzcwpx0bRZVIbcGJ45/GqRwFjMfq8PJ+k7ZWsNMic0EMBgP33FOq9MFKX0XE/a1plhDizbb92ErQYw==
   
  
 

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

public partial class Startup
{
  public void Configuration(IAppBuilder app)
  {
    var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\keyPath\"));
    var dataProtector = protectionProvider.CreateProtector("MyCookieAuthentication");
    var ticketFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));
      
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
      AuthenticationType = "test",
      CookieName = "MyCookie",
      CookieDomain = "localhost",
      TicketDataFormat = ticketFormat
    });
  }
}

view




  .net framewor欢迎您-@User.Identity.Name


  @if (User.Identity.IsAuthenticated)
  {
    

.net framework登录成功!

  }

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

如何使ASP.NETCore和ASP.NETFramework共享身份验证

反之在.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上也没找到其源码,瞎忙活了一阵之后终于感慨:臣妾做不到(>﹏< )。

Cookie认证的相关属性

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
  AuthenticationScheme = "test",
  CookieName = "MyCookie",
  CookieDomain = "localhost",
  TicketDataFormat = new FormsAuthTicketDataFormat("")
});

FormsAuthTicketDataFormat

public class FormsAuthTicketDataFormat : ISecureDataFormat
{
  private string _authenticationScheme;

  public FormsAuthTicketDataFormat(string authenticationScheme)
  {
    _authenticationScheme = authenticationScheme;
  }

  public AuthenticationTicket Unprotect(string protectedText, string purpose)
  {
    var formsAuthTicket = GetFormsAuthTicket(protectedText);
    var name = formsAuthTicket.Name;
    DateTime issueDate = formsAuthTicket.IssueDate;
    DateTime expiration = formsAuthTicket.Expiration;

    var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "Basic");
    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

    var authProperties = new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties
    {
      IssuedUtc = issueDate,
      ExpiresUtc = expiration
    };
    var ticket = new AuthenticationTicket(claimsPrincipal, authProperties, _authenticationScheme);
    return ticket;
  }

  FormsAuthTicket GetFormsAuthTicket(string cookie)
  {
    return DecryptCookie(cookie).Result;
  }

  async Task DecryptCookie(string cookie)
  {
    HttpClient _httpClient = new HttpClient();
    var response = await _httpClient.GetAsync("http://192.168.190.134/user/getMyTicket?cookie={cookie}");
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsAsync();
  }
}

FormsAuthTicket

public class FormsAuthTicket
{
  public DateTime Expiration { get; set; }
  public DateTime IssueDate { get; set; }
  public string Name { get; set; }
}

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

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

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

[HttpPost]
public async Task Login(string name)
{
  HttpClient _httpClient = new HttpClient();
  var response = await _httpClient.GetAsync($"http://192.168.190.134/user/getMyCookie?name={name}");
  response.EnsureSuccessStatusCode();

  string cookieValue = (await response.Content.ReadAsStringAsync()).Trim('\"');
  CookieOptions options = new CookieOptions();
  options.Expires = DateTime.MaxValue;
  HttpContext.Response.Cookies.Append("MyCookie", cookieValue, options);

  return RedirectToAction("Index");
}

webapi获取cookie

[Route("getMyCookie")]
public string GetMyCookie(string name)
{
  FormsAuthentication.SetAuthCookie(name, false);
  return FormsAuthentication.GetAuthCookie(name, false).Value;
}

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

如何使ASP.NETCore和ASP.NETFramework共享身份验证

ok,登录成功,至此完成.net framework和.net core身份验证的兼容。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...