2

我已经使用过表单身份验证,已在different sites之间,甚至between different versions of .NET,但现在我们正在研究开始一个新项目 ASP.NET 5(MVC 6) ASP.NET Core,并希望跨两者使用基于cookie的表单身份验证。登录是在“旧”MVC 5应用程序中完成的。基于Cookie的MVC 5和ASP.NET核心应用程序的身份验证

是对基于cookie的窗体身份验证甚至有可能或ASP.NET 5的当前版本支持一些跨应用程序的配置? 难道这是在 MVC6 ASP.NET核心侧使用FormsAuthenticationModule实现,或者可以将它与新authentication middleware莫名其妙一起玩?还有其他建议吗?

回答

0

的WebForms不是ASP.NET 5. This is change #2 according to this blog post

的一部分更新

ASP.NET MVC 6的新的生命周期使用中间件组成的服务。您可以使用Security包进行身份验证,但旧的“表单”身份验证不再受支持。

+0

你眼花缭乱方面一点。这不绑定到WebForms。 [表单身份验证](https://msdn.microsoft.com/en-us/library/7t6b43z4(v = vs.140).aspx)是一种使用ASP.NET(pre vNext)进行身份验证的方法,也用于由MVC。它是System.Web程序集(System.Web.Security命名空间)的一部分,它可以被MVC6(在dnx上)引用。但是,如果这是我可以/应该做的事情,我不确定,因为在MVC6中进行身份验证的方式似乎与新的[身份验证中间件](https://github.com/aspnet/Security)一样。我会更新一个问题,使其更清晰。 –

+0

好的。无论哪种方式,似乎不再支持表单验证(至少从beta 4开始)。 – natemcmaster

2

我一直在打我的头在过去这几天同样的问题...但我已经解决了它......(似乎持股待涨)

这是一个转换的窗口和后来的形式身份验证以MVC5和MVC6身份验证,希望您可以更改足够的代码以使其适用于您...我计划在重新编写登录脚本时更改某些部分。 (这是阿尔法那么将进行一些改变!)

我把下面的代码在我们MVC5内联网站抢角色对于Windows身份验证

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) 
    { 
     // Get current windows Identity to get the roles out of it 
     WindowsIdentity ident = WindowsIdentity.GetCurrent(); 

     string[] roles = new string[ident.Groups.Count]; 
     int i = 0; 

     // get the groups from the current Identity 
     foreach (var g in ident.Groups) 
     { 

      roles[i] = g.Translate(typeof(System.Security.Principal.NTAccount)).Value.ToString(); 
      i++; 
     } 

     // join into a single string the roles that the user is a member of 
     string roleData = String.Join(";", roles) ; 

     // create the forms ticket that all MVC5 sites with the same machine key will pick up. 
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, ident.Name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roleData, "/"); 
     string encTicket = FormsAuthentication.Encrypt(ticket); 


     // add the user name first from the Principle and add Windows as this will come from Windows Auth 
     roleData = ident.Name + ";" + "Windows;" + roleData; 

     //use machine key to encrypt the data 
     var encTicket2 = MachineKey.Protect(System.Text.Encoding.UTF8.GetBytes(roleData), 
      "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware", 
      "ApplicationCookie", "v1"); 

     //create a new cookie with a base64string of the encrypted bytes 
     HttpCookie hc2 = new HttpCookie("cookie1", Convert.ToBase64String(encTicket2)); 
     hc2.Domain = ".domain.com"; 
     hc2.Expires = DateTime.Now.AddHours(8); 
     Response.Cookies.Add(hc2); 

     // NOTE: The name of the HttpCookie must match what the FormsAuth site expects. 
     HttpCookie hc = new HttpCookie("cookie2", encTicket); 
     hc.Domain = ".domain.com"; 
     hc.Expires = DateTime.Now.AddHours(8); 
     Response.Cookies.Add(hc); 
     // Ticket and cookie issued, now go to the FormsAuth site and all should be well. 
     Response.Redirect("http://www.yoursite.com"); 
    } 

这将创建一个Windows身份验证票证这两种形式和MVC6方法。

的字符串MVC6看起来像“John.Doe;视窗;联系”

然后在MVC6启动文件我已经把下面的代码到配置部分...

 app.Use(async (context, next) => 
     { 
      Logger _logger = new Logger("C:\\\\Logs\\Log.txt"); 
      try 
      { 

       var request = context.Request; 
       var cookie = request.Cookies.Get("cookie1"); 
       var ticket = cookie.ToString(); 

       ticket = ticket.Replace(" ", "+"); 

       var padding = 3 - ((ticket.Length + 3)%4); 
       if (padding != 0) 
        ticket = ticket + new string('=', padding); 

       var bytes = Convert.FromBase64String(ticket); 
       bytes = System.Web.Security.MachineKey.Unprotect(bytes, 
        "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware", 
        "ApplicationCookie", "v1"); 

       string ticketstring = System.Text.Encoding.UTF8.GetString(bytes); 

       var ticketSplit = ticketstring.Split(';'); 

       var claims = new Claim[ticketSplit.Length]; 

       var OriginalIssuer = ""; 

       for (int index = 0; index != ticketSplit.Length; ++index) 
       { 

        if (index == 0) 
        { 
         claims[index] = new Claim(ClaimTypes.Name, ticketSplit[index], "Windows"); 
        } 
        else if (index == 1) 
        { 
         OriginalIssuer = ticketSplit[1]; 
        } 
        else 
        { 
         claims[index] = new Claim(ClaimTypes.Role,ticketSplit[0], OriginalIssuer); 
        } 
       } 

       var identity = new ClaimsIdentity(claims, OriginalIssuer, ClaimTypes.Name,ClaimTypes.Role); 

       var principal = new ClaimsPrincipal(identity); 

       _logger.Write(principal.Identity.Name); 

       context.User = principal; 
       _logger.Write("Cookie End"); 
       await next(); 
      } catch (Exception ex) 
      { 
       _logger.Write(ex.Message); 
       _logger.Write(ex.StackTrace); 
      } 
     }); 

然后接受cookie并从中创建新的声明标识。我只是完成了逻辑来让它工作,所以我确信它可以被整理...只是想我会把它给你,所以你可以看看你是否可以得到一些关于它的想法。

+0

太棒了!感谢您的输入。我们暂时搁置了这个想法,但我会试试看。你是否依赖于任何地方的'Microsoft.Owin.Security'软件包,还是只将它用作目的参数? –

+0

老实说,不能确定从一个非常古老的代码示例中偷走了这行代码......并且它似乎在工作中太害怕而无法破解它......我们正在试用此代码,并且发生了一些小的变化(上述代码中的一些错误以及表单中的一些部分略有改动)。我们也正在从会员身份转向身份! – Kisbys

+1

Ps我可以给你一些更新的代码,如果你想或等待约48小时,当扭曲应该已经通过?让我知道:) – Kisbys

0

这是我在Asp中的简单代码。网络核心的MVC,希望能帮助:

Startup.cs 在功能ConfigureServicesservice.AddMvc()

添加services.AddAuthorization();在功能Configure添加如下代码这个

app.UseCookieAuthentication(new CookieAuthenticationOptions 
      { 
       AuthenticationScheme = "UserLoginCookie", 
       LoginPath = new PathString("/Account/Login"), 
       AccessDeniedPath = new PathString("/Account/Forbidden"), 
       AutomaticAuthenticate = true, 
       AutomaticChallenge = true 
      }); 

app.UseMvc....

在登录方法: 核心代码是这样的:

 var claims = new List<Claim>() 
     { 
      new Claim(ClaimTypes.Name,userName here), 
      new Claim("UserCodeInMyWebApp",Anything you want), 
      new Claim(ClaimTypes.Role,"Admin") 

     }; 
      var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "UserLoginClaimsIdentity")); 
      //signin 
      await HttpContext.Authentication.SignInAsync("UserLoginCookie", userPrincipal, new AuthenticationProperties 
      { 
       ExpiresUtc = DateTime.UtcNow.AddMinutes(20), 
       IsPersistent = false, 
       AllowRefresh = false 
      }); 

      return RedirectToAction("AuthPage", "Home"); 

则可以通过键值访问要求值或检查证实:

bool flag = User.Identity.IsAuthenticated 
ClaimsIdentity user = User.Identity as ClaimsIdentity 
user.Name or user.FindFirst(the key value string you created).Value 

,并检查这样的:

[HttpGet] 
     [AllowAnonymous] 
     public IActionResult Index() 
     { 
      return View(); 
     } 

     [Authorize(Roles = "Admin")] 
     [HttpGet] 
     public IActionResult AuthPage() 
     { 
      return View(); 
     } 

     public IActionResult About() 
     { 
      return View(); 
     } 
相关问题