gpt4 book ai didi

.net - 基于权限的授权.net 身份

转载 作者:行者123 更新时间:2023-12-02 02:38:53 29 4
gpt4 key购买 nike

我是 .NET、MVC 和身份框架的新手。我注意到身份框架允许通过注释保护单个 Controller 操作。

[Authorize]
public ActionResult Edit(int? Id){
//edit action
}

我想根据用户权限保护某些操作。

示例:一个博客应用程序,只有创建博客文章的用户才能编辑。

考虑到这一点,是否可以执行以下任一选项?如果是这样,是否有关于如何最好地实现目标的资源和示例?

[Authorize(Entity = "Entry", Permission = "Edit", Id = Id)]
public ActionResult Edit(int? Id){
//edit action
}

[BlogEntryPermission(Permission = "Edit", Id = Id)]
public ActionResult Edit(int? Id){
//edit action
}

从请求中捕获博客 Id 的位置。

任何有关基于权限的身份验证的信息或指示将不胜感激。在此先感谢您的帮助。

最佳答案

您可以实现自定义AuthorizationAttribute,您将在其中指定参数并可以从请求获取blogId

public class AuthorizeEntryPermission : AuthorizeAttribute
{
public string Permission { get; set; }

public AuthorizeEntryPermission(){
}

public AuthorizeEntryPermission(string Permission)
{
this.Permission = Permission;
}

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var id = context.Request.RequestContext.RouteData.Values["Id"];
//check your permissions
}

public override void OnAuthorization(AuthorizationContext filterContext)
{
if (AuthorizeCore(filterContext.HttpContext))
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.

HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else
{
//handle no permission
}
}

private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}

然后像这样使用它:

[AuthorizeEntryPermission(Permission = "Edit")]
public ActionResult Edit(int? Id){
//edit action
}

关于.net - 基于权限的授权.net 身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27047982/

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