gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:09:09 26 4
gpt4 key购买 nike

我有我的行动方法

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

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

最佳答案

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

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

然后用它装饰你的 Controller Action :

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

关于c# - 如何为角色和特定用户使用自定义授权属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11493873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com