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(); 
     } 
相關問題