2009-11-05 132 views
0

我用这段代码看到的问题是,它将被重用很多;任何被认证用户(除了网站管理员)编辑/创建的内容都只能访问他们的“工作室”对象。ASP.NET MVC - 授权重构

我的问题给大家;你将如何重新考虑这一点,以便服务层可以从客户的知识中抽象出来。我打算稍后在独立桌面应用程序中重用服务层。

请阐明我错误的方式!我非常感谢。

AuthorizeOwnerAttribute.cs(AuthorizeAttribute)

protected override bool AuthorizeCore(HttpContextBase httpContext) 
{ 
    // Get the authentication cookie 
    string cookieName = FormsAuthentication.FormsCookieName; 
    HttpCookie authCookie = httpContext.Request.Cookies[cookieName]; 

    // If the cookie can't be found, don't issue the ticket 
    if (authCookie == null) return false; 

    // Get the authentication ticket and rebuild the principal & identity 
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
    string[] userData = authTicket.UserData.Split(new[] { '|' }); 

    int userId = Int32.Parse(userData[0]); 
    int studioID = Int32.Parse(userData[1]); 
    GenericIdentity userIdentity = new GenericIdentity(authTicket.Name); 
    WebPrincipal userPrincipal = new WebPrincipal(userIdentity, userId, studioID); 
    httpContext.User = userPrincipal; 

    return true; 
} 

内部我的 “用户” 控制器此属性附加到需要一个所有者的任何方法的现在

[AuthorizeOwner] 
    public ActionResult Edit(int Id) 
    { 
     IUser user = userService.GetById(HttpContext.User, Id); 
     return View(user); 
    } 

,在我的服务层是我正在检查传入的IPrincipal是否有权访问请求的对象。 这是它变得臭:

UserService.cs

public IUser GetById(IPrincipal authUser, int id) 
    { 
     if (authUser == null) throw new ArgumentException("user"); 

     WebPrincipal webPrincipal = authUser as WebPrincipal; 
     if (webPrincipal == null) throw new AuthenticationException("User is not logged in"); 

     IUser user = repository.GetByID(id).FirstOrDefault(); 
     if (user != null) 
     { 
      if (user.StudioID != webPrincipal.StudioID) throw new AuthenticationException("User does not have ownership of this object"); 
      return user; 
     } 

     throw new ArgumentException("Couldn't find a user by the id specified", "id"); 
    } 

回答

2

我不知道我会被存储在cookie中的实际的ID,这有点太暴露。我更倾向于使用会话哈希来存储数据,从而保持它在服务器上,而不是暴露。

我也会使用Model(通过传递userID)来确定要返回哪些对象,即那些具有匹配studioID的对象。这样,如果你的控制器没有权限访问任何东西,那么你只需要调用“GetObjects(int id)”,那么你就会得到一个空的或空的集合。这让我感觉更清洁。

+0

你能详细讲解会话哈希部分吗? – 2009-11-05 15:41:23

+0

看看这里:http://msdn.microsoft.com/en-us/library/ms178581.aspx – Lazarus 2009-11-05 16:13:13

+0

你能给我一个使用会话哈希的例子吗?我不确定我是否关注你。哪里来玩? – 2009-11-05 17:02:29