.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<IActionResult> Login(string name)
{
    var identity = new ClaimsIdentity(
                    new List<Claim>
                    {
                    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 视图

<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
</head>
<body>
    <form asp-controller="Account" asp-action="Login" method="post">
       <input type="text" name="name" /><input type="submit" value="提交" />
    </form>
</body>
</html>

index 视图

<!DOCTYPE html>
<html>
<head>
  <title>欢迎您-@User.Identity.Name</title>
</head>
<body>
    @if (User.Identity.IsAuthenticated)
    {
        <p>登录成功!</p>
    }
</body>
</html>

下面是实现效果的截图:

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

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

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

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

<!DOCTYPE html>
<html>
<head>
    <title>.net framewor欢迎您-@User.Identity.Name</title>
</head>
<body>
    @if (User.Identity.IsAuthenticated)
    {
        <p>.net framework登录成功!</p>
    }
</body>
</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认证的相关属性

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

FormsAuthTicketDataFormat

public class FormsAuthTicketDataFormat : ISecureDataFormat<AuthenticationTicket>
{
    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<FormsAuthTicket> 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>();
    }
}

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<IActionResult> 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,我们来测试一下

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. linux平台上面python调用c

    不能免俗,先打印个helloworld出来,c代码的函数 hello.c #include <stdio.h> int helloworld() { printf("hello ...

  2. iOS网络

    iOS开发系列--网络开发 2014-10-22 08:34 by KenshinCui, 1253 阅读, 19 评论, 收藏,  编辑 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微 ...

  3. 你一定要知道的关于Linux文件目录操作的12个常用命令

    写在前面: 1,<你一定要知道的关于Linux文件目录操作的12个常用命令>是楼主收集的关于Linux文件目录操作最常用的命令,包括文件或目录的新建.拷贝.移动.删除.查看等,是开发人员操 ...

  4. 零基础学redis

    第一个阶段:redis基本知识了解: 1. redis的百度百科解释: Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言 ...

  5. angularjs编码实践

    AngularJS 是制作 SPA(单页面应用程序)和其它动态Web应用最广泛使用的框架之一.我认为程序员在使用AngularJS编码时有一个大的列表点应该记住,它会以这样或那样的方式帮助到你.下面是 ...

  6. bower的权限问题

    装bootstrap的时候,先用sudo指令装了bower,但是一打 bower isntall bootstrap 就报错: Error: EACCES, permission denied '/U ...

  7. VSFTP被动模式

    搞了几个弯路,各种办法都试了. 动静最小的,还是定义端口. 还有虚拟用户,配置太多,只适用于小范围吧.又要pam.d,又要chroot之类的,nologin也必不可少. ~~~~~~~~~ 限制被动模 ...

  8. php的ob实现页面静态化

    php页面静态化的原理,用最少的代码解释页面静态化 如何应用:在插入或更新数据到数据库时,就执行一下代码是一种比较好的方法.比如:php执行add()方法时(就是插入数据时) //开启缓存 Ob_st ...

  9. Delphi中代替WebBrowser控件的第三方控件

    这几天,接触到在delphi中内嵌网页,用delphi7自带的TWebBrowser控件,显示的内容与本机IE8显示的不一样,但是跟装IE8之前的IE6显示一个效果.现在赶脚是下面两个原因中的一个: ...

  10. 通过 PowerShell 支持 Azure Traffic Manager 外部端点和权重轮询机制

    Jonathan TulianiAzure网络 - DNS和 Traffic Manager高级项目经理 在北美 TechEd 大会上,我们宣布了 Azure Traffic Manager将支持 ...