1

如何确保只有在博客中创建帖子的用户才能删除或编辑它?

即用户可以创建博客文章并可以在/post/edit/{ID}. 如果用户将不属于他的帖子的 id 更改为其他不同的值怎么办?

如何确保他要编辑的帖子只属于他?

4

1 回答 1

2

您可以编写一个自定义Authorize属性,您将在其中查询您的数据库,以确保当前连接的用户是他试图修改的博客文章的作者:

public class EnsureAuthorOfBlogAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        string blogId = httpContext.Request.RequestContext.RouteData.Values["id"] as string;
        string username = httpContext.User.Identity.Name;
        return IsBlogAuthor(username, blogId);
    }

    private bool IsBlogAuthor(string username, string blogId)
    {
        // TODO: you know what to do here
        throw new NotImplementedException();
    }
}

然后用这个自定义属性装饰控制器动作:

[HttpDelete]
[EnsureAuthorOfBlog]
public ActionResult Delete(int id)
{
    ...
}

和编辑一样:

[HttpPut]
[EnsureAuthorOfBlog]
public ActionResult Update(BlogViewModel blog)
{
    ...
}
于 2012-08-19T06:55:06.397 回答