mcr*_*eau 8 .net asp.net-mvc user-permissions asp.net-identity
我是.NET,MVC和Identity Framework的新手.我注意到身份框架允许通过注释保护单个控制器操作.
[Authorize]
public ActionResult Edit(int? Id){
//edit action
}
Run Code Online (Sandbox Code Playgroud)
我想根据用户权限确保某些操作.
示例:只有创建博客文章的用户才能编辑的博客应用程序.
考虑到这一点,是否可以执行以下任一选项?如果是这样,是否有关于如何最好地实现的资源和示例?
[Authorize(Entity = "Entry", Permission = "Edit", Id = Id)]
public ActionResult Edit(int? Id){
//edit action
}
Run Code Online (Sandbox Code Playgroud)
要么
[BlogEntryPermission(Permission = "Edit", Id = Id)]
public ActionResult Edit(int? Id){
//edit action
}
Run Code Online (Sandbox Code Playgroud)
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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
[AuthorizeEntryPermission(Permission = "Edit")]
public ActionResult Edit(int? Id){
//edit action
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8494 次 |
| 最近记录: |