如何实现自定义授权属性下面的案例?自定义、如何实现、属性、案例

2023-09-02 10:35:54 作者:是男人就像爷们一样

让我有我的操作方法

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

在我来说,我需要授权管理员,以便他们可以编辑的职位,但(这里来了凉爽的一部分),我还需要允许的帖子创建者能够编辑帖子至极是一个普通用户。那么,如何可以筛选出创造的职位还有管理员用户,但保留其他未经授权的?我recieveing​​的后补ID作为路由参数,但是在属性附加伤害后,多数民众赞成,也属性只接受常量参数,看起来像是很困难的,你的答案是非常AP preciated,干杯!

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 wich 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 recieveing the PostEntry id as a route parameter but thats after the atribute 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();
}