我与此代码看,问题是,它要被重复使用很多;任何被编辑/通过身份验证的用户(除网站管理员)创建只能访问到他们的“工作室”的对象。

我给你所有的问题;你将如何重新因素会这样的服务层可以从客户端的知识抽象出来。我打算以后再次在一个独立的桌面应用程序的服务层。

请阐明了我的错误的方式一些轻!我不胜感激。

<强> 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");
    }
有帮助吗?

解决方案

我不知道我会被存储在cookie中的实际的ID,这有点太暴露。我会更倾向于使用会话散列来存储由此该数据保持它在服务器上并且不暴露。

我还使用模型(通过将用户ID),以确定哪些对象返回,即,那些具有匹配studioID。控制器只会曾经有叫“GetObjects(INT ID)”,如果他们没有获得任何的方式,那么你得到一个空或空回。那种感觉清洁剂给我。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top