2012-03-04 79 views
0

我正在构建一个Asp.net MVC3应用程序(使用Razor),并且我有一个包含用户和角色信息的数据库。如何使用其他数据库和会话进行授权?

这是我的数据库的简化方案。

用户(IDUser,登录,密码);
角色(IDRole,Name);
UserInRole(IDUser,IDRole); //多对多

是这样的:

db schema screnshot

我读到关于使用AuthorizeAttribute,来控制loged用户的网页,并与特定角色和我的研究有关使用我的数据库来控制用户和角色。所以我的问题是:

  1. 是否可以使用我的数据库来管理用户和角色,并在我的操作中使用[授权]? [如果是,我该怎么做?]
  2. 是否可以使用session来代替cookie来管理登录并使用Authorization native Asp.net MVC3? [如果是的话,我该怎么做?如果没有如何使用会话,否则?]

如果可能请张贴代码示例。

回答

0

谢谢佩德罗。根据你的文章,我建立这个使用SESSION:

public class CustomAutorizeAttribute : AuthorizeAttribute 
{ 
    public List<string> Roles { get; set; } 

    public CustomAutorizeAttribute() 
    { 
    } 

    public CustomAutorizeAttribute(params string[] Roles) 
    { 
     this.Roles = new List<string>(); 
     this.Roles.AddRange(Roles); 
    } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     User user = (User)httpContext.Session["user"]; 

     if (user != null) 
     { 
      if (Roles != null) 
      { 
       foreach (var role in user.Roles) 
       { 
        if (Roles.Exists(e => e == role)) return true; 
       } 
       return false; // User don't have any hole 
      } 
      else 
      { 
       return true; // The Attribute is used without roles. 
      } 
     } 
     else return false; // Not logged. 
    } 
} 

张贴在这里希望别人。

1

不知道我是否理解正确,但您想使用[Authorize]属性来处理您的自定义用户数据库?

如果是这样的话,也有出头检查:

要简单地允许/拒绝基于用户是否被授权与否,股票[Authorize]属性会工作得很好。自定义逻辑进入登录操作,您将在其中使用给定的凭据检查数据库并相应地发出cookie。喜欢的东西:

public ActionResult Login(string username, string password) 
    { 
     bool isValid = //check the database with the given username and password 

     if(isValid) 
     { 
      FormsAuthentication.SetAuthCookie(username, false); 

      return RedirectToAction("..."); 
     }else 
     { 
      return View(); 
     } 
    } 

如果您想根据角色来也控制访问,我要说有2种直接的方式:

  • 实现自定义成员资格和角色提供者,这是我不像,因为我觉得他们很没用,最后总是在我respositories重做逻辑

  • 实现自定义AuthorizeAttribute,像

    public class CustomAuthorizeAttribute : AuthorizeAttribute 
    { 
        protected override bool AuthorizeCore(HttpContextBase httpContext) 
        { 
         //Check based on these 2 properties: 
         // this.Roles 
         // this.Users 
         //against httpContext.User 
    
         //return true or false to indicate access or deny 
        } 
    } 
    
+0

非常感谢您的光临。但我还有一个问题FormsAuthentication与Session或Cookie一起使用? – 2012-03-10 23:27:54

相关问题