MVC4授权特定用户

时间:2014-02-11 13:32:02

标签: asp.net-mvc-4

我有一个非常简单的论坛,我创建帖子。现在我想只为创建帖子和管理员的用户授权编辑功能。

仅限管理员,这很容易:

[Authorize(Roles = "Administrator,Moderator")]

@if (Roles.IsUserInRole("Administrator")){}

但我不知道如何为特定的登录用户制作它。

1 个答案:

答案 0 :(得分:1)

按照您目前的授权进行授权。这将照顾管理员和主持人。

然后,在从数据存储中检索帖子时执行类似的操作。要么是这样的:

var post = repository.Posts.Where(p => p.Id == parameterPostId && p.CreatedBy == CurrentUser.UserName).FirstOrDefault();
if (post == null) {
    // User didn't create it. return false or unauthorized.
}
else {
    // Continue on with returning the post.
}

或者,您也可以这样做以确保数据库中的帖子完全存在:

var post = repository.Posts.Where(p => p.Id == parameterPostId).FirstOrDefault();
if (post == null) 
    // You know the post doesn't exist at all.
}
else if (post.CreatedBy != CurrentUser.UserName) {
    // The post was made by someone else, so unauthorized
}
else {
    // Show the user their post.
}