2014-01-28 44 views
0
<authorization> 
    <allow roles = "Admin" /> 
    <deny users="?"/> 
</authorization> 

角色分配角色的身份驗證工作不使用asp.net mvc4

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) 
    { 
     if (FormsAuthentication.CookiesSupported == true) 
     { 
      if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) 
      {  
       string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; 
       string roles = string.Empty; 
       bool check; 
       using (RealEstateEntities db = new RealEstateEntities()) 
       { 
        check = db.Admins.Any(model => model.Roles == "Admin" && model.UserName == username); 
       } 
       if (check) 
        roles = "Admin"; 
       else 
        roles = "User"; 
       // GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(username,"Forms"), roles); 
       Context.User = new GenericPrincipal(new GenericIdentity(username, "Forms"), roles.Split(';')); 
      } 
     } 
    } 

的Global.asax

[Authorize(Roles = "Admin")] 

* 但它不工作*

[Authorize(Users = "Abid")] 

它適用於當我在web配置中將角色更改爲用戶時 我是mvc4 plz的新手幫助!

回答

0

在asp.net MVC 4中,你不應該在你的web.config文件中使用授權(除非你想保護自定義文件夾)。

您應該註冊一個全球性的過濾器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new System.Web.Mvc.AuthorizeAttribute()); 
} 

,並使用AllowAnonymous當你不希望任何形式的授權,爲你的行動。

你可以找到詳細的解釋hereherehere

這個article顯示了不同的asp.net版本之間的區別。

希望它有幫助。

+0

「你不應該在你的web.config文件中使用授權」 - 這是如何處理Content文件夾中的靜態內容的? – Joe

+0

好點。如果你使用捆綁,你不必使用web.config,否則你是對的,你必須使用它。 – LeftyX

+0

感謝您的幫助 –

相關問題