在我的 Web 应用程序中,注册用户可以添加新内容并稍后进行编辑。我只希望内容的作者能够编辑它。除了在所有操作方法中手动编写代码来检查登录用户是否与作者相同之外,还有什么聪明的方法可以做到这一点?我可以为整个控制器使用的任何属性?
问问题
2014 次
2 回答
6
我可以为整个控制器使用的任何属性?
Authorize
是的,您可以使用自定义属性扩展属性:
public class AuthorizeAuthorAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
// the user is either not authenticated or
// not in roles => no need to continue any further
return false;
}
// get the currently logged on user
var username = httpContext.User.Identity.Name;
// get the id of the article that he is trying to manipulate
// from the route data (this assumes that the id is passed as a route
// data parameter: /foo/edit/123). If this is not the case and you
// are using query string parameters you could fetch the id using the Request
var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string;
// Now that we have the current user and the id of the article he
// is trying to manipualte all that's left is go ahead and look in
// our database to see if this user is the owner of the article
return IsUserOwnerOfArticle(username, id);
}
private bool IsUserOwnerOfArticle(string username, string articleId)
{
throw new NotImplementedException();
}
}
进而:
[HttpPost]
[AuthorizeAuthor]
public ActionResult Edit(int id)
{
... perform the edit
}
于 2012-04-09T06:40:48.597 回答
0
我会:
- 根据内容记录保存 db.aspnet_Users 列 UserId (Guid)
- 为您的内容模型编写一个扩展方法,根据保存的内容 User Guid 验证当前用户 Guid
- 我将为您的管理员登录编写一些代码来覆盖此功能(我将创建一个管理员角色)。
于 2012-04-08T17:43:49.540 回答