首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为角色和特定用户使用自定义授权属性?

如何为角色和特定用户使用自定义授权属性?
EN

Stack Overflow用户
提问于 2012-07-16 01:02:23
回答 1查看 55.8K关注 0票数 35

我有我的操作方法

代码语言:javascript
运行
复制
[Authorize(Roles="Admin")]
public ActionResult EditPosts(int id)
{
    return View();
}

在我的情况下,我需要授权管理员,以便他们可以编辑帖子,但(这里是很酷的部分),我还需要允许帖子的创建者能够编辑普通用户的帖子。那么,我如何过滤掉创建帖子的用户和管理员,而让其他用户保持未授权状态?我收到了PostEntry id作为路由参数,但这是在属性之后,属性也只接受常量参数,看起来很困难,你的回答非常感谢,干杯!

EN

Stack Overflow用户

回答已采纳

发布于 2012-07-16 01:30:43

您可以编写一个自定义的authorize属性:

代码语言:javascript
运行
复制
public class AuthorizeAdminOrOwnerOfPostAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authenticated
            return false;
        }

        var user = httpContext.User;
        if (user.IsInRole("Admin"))
        {
            // Administrator => let him in
            return true;
        }

        var rd = httpContext.Request.RequestContext.RouteData;
        var id = rd.Values["id"] as string;
        if (string.IsNullOrEmpty(id))
        {
            // No id was specified => we do not allow access
            return false;
        }

        return IsOwnerOfPost(user.Identity.Name, id);
    }

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

然后用它来装饰你的控制器动作:

代码语言:javascript
运行
复制
[AuthorizeAdminOrOwnerOfPost]
public ActionResult EditPosts(int id)
{
    return View();
}
票数 72
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11493873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档