Dot-Net
基於權限的授權.net 身份
我是 .NET、MVC 和身份框架的新手。我注意到身份框架允許通過註釋保護單個控制器操作。
[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 }