Asp.net-Mvc

向 MVC 3 添加基於聲明的授權

  • December 30, 2013

我有一個想要添加基於聲明的授權的 MVC 應用程序。在不久的將來,我們將使用 ADFS2 進行聯合身份驗證,但現在我們將在本地使用表單身份驗證。

有沒有人看過關於在沒有外部身份提供者的情況下使用 WIF 的最佳方法的教程或部落格文章?

我已經看到了以下內容,但它現在已經一歲了,我認為應該有一個更簡單的解決方案:

<http://geekswithblogs.net/shahed/archive/2010/02/05/137795.aspx>

您可以在沒有 STS 的情況下在 MVC 中使用 WIF。

我使用了預設的 MVC2 模板,但它也應該適用於 MVC 3。

你需要:

1-插入 WIF 的SessionAuthenticationModule (web.config)

&lt; add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt;

2-無論您在哪裡驗證您的使用者,創建一個ClaimsPrincipal,添加所有必需的聲明,然後創建一個SessionSecurityToken。這是MVC 創建的AccountController中的LogOn Action :

[HttpPost]
       public ActionResult LogOn(LogOnModel model, string returnUrl)
       {
           if (ModelState.IsValid)
           {
               if (MembershipService.ValidateUser(model.UserName, model.Password))
               {
                   var cp = new ClaimsPrincipal();
                   cp.Identities.Add(new ClaimsIdentity());
                   IClaimsIdentity ci = (cp.Identity as IClaimsIdentity);

                   ci.Claims.Add(new Claim(ClaimTypes.Name, model.UserName));

                   SessionSecurityToken sst = FederatedAuthentication
                       .SessionAuthenticationModule
                       .CreateSessionSecurityToken(cp,
                                                   "MVC Test",
                                                   DateTime.
                                                       UtcNow,
                                                   DateTime.
                                                       UtcNow.
                                                       AddHours
                                                       (1),
                                                   true);


                   FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl = false;
                   FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(sst, true);


                   //FormsService.SignIn(model.UserName, model.RememberMe);
                   if (!String.IsNullOrEmpty(returnUrl))
                   {
                       return Redirect(returnUrl);
                   }
                   else
                   {
                       return RedirectToAction("Index", "Home");
                   }
               }
               else
               {
                   ModelState.AddModelError("", "The user name or password provided is incorrect.");
               }
           }

           // If we got this far, something failed, redisplay form
           return View(model);
       }

我只是添加了所需的行,其他一切都保持不變。所以可能需要進行一些重構。

從那裡開始,您的應用程序現在將收到ClaimsPrincipal。全部由 WIF 自動處理。

CookieHandler.RequiresSsl = false只是因為它是開發機器,我沒有在 IIS 上部署。它也可以在配置中定義。

引用自:https://stackoverflow.com/questions/5997848