如何为角色以及特定用户使用自定义授权属性? [英] How to use custom Authorize attribute for roles as well as a specific user?

查看:24
本文介绍了如何为角色以及特定用户使用自定义授权属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的行动方法

[Authorize(Roles="Admin")]
public ActionResult EditPosts(int id)
{
    return View();
}

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

In my case I need to authorize administrators so they can edit posts but (here comes the cool part), I also need to allow the creator of the post to be able to edit the post which is a normal user. So how can I filter out the user that created the post as well as the admins but leave the others unauthorized? I am receiving the PostEntry id as a route parameter but that's after the attribute and also attributes only accept constant parameters, looks like something very difficult, your answers are highly appreciated, Cheers!

推荐答案

您可以编写自定义授权属性:

You could write a custom authorize attribute:

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();
    }
}

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

and then decorate your controller action with it:

[AuthorizeAdminOrOwnerOfPost]
public ActionResult EditPosts(int id)
{
    return View();
}

这篇关于如何为角色以及特定用户使用自定义授权属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆