2011-05-13 27 views
16

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

有沒有人看過有關在沒有外部身份提供程序的情況下使用WIF的最佳方式的教程或博客文章?

我看到了下面卻是一年,現在的老,我覺得應該有一個簡單的解決方案:

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

回答

21

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

我使用了默認的MVC2模板,但它也應該與MVC 3一起工作。

您需要:

1-插件WIF的SessionAuthenticationModule(web.config中)

< add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 

2 - 無論你驗證你的用戶,創建一個ClaimsPrincipal ,添加所有要求的索賠,然後創建一個SessionSecurityToken。這是的AccountController通過MVC創建LogOn支持操作:

[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 =假僅僅是因爲它是一個dev的機器,我不會在IIS上部署。它也可以在配置中定義。

+0

那麼你如何去添加另一個身份提供者?像谷歌或adfs? – BentOnCoding 2012-09-01 06:07:17

1

WIF設計使用STS,所以如果你不想做到這一點,那麼你必須根據文章重新發明輪子。

當你移動到ADFS時,你幾乎不得不重新編碼一切。

或者,看看StarterSTS,這實現了您需要的同一種aspnetdb身份驗證,但允許WIF執行繁重的操作。然後,當你遷移到ADFS時,你只需要針對ADFS運行FedUtil,它將在沒有任何重大編碼改變的情況下運行。

(順便說一句,有一個MVC版本 - 稍後實現 - here)。