2017-06-08 61 views
1

由於我在Asp.Net core Authorization部分工作,我需要一個新屬性AuthorizeAttribute,我想將其用作額外的權限值。所以,我已將AuthorizeAttribute擴展到我自己的自定義「授權」屬性中。請看下圖:Asp.Net Core:訪問AuthorizeHandler中的自定義AuthorizeAttribute屬性

public class RoleAuthorizeAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute 
    { 
     public string Permission { get; private set; } 

     public RoleAuthorizeAttribute(string policy, string permission) : base(policy) 
     { 
      this.Permission = permission; 
     } 
    } 

然後,我創建了一個AuthorizationHandler檢查如下要求:

public class RolePermissionAccessRequirement : AuthorizationHandler<RolePermissionDb> 
    { 
     protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolePermissionDb requirement) 
     { 
      // check here.. 
      context.Succeed(requirement); 

      return Task.FromResult(0); 
     } 
    } 

所有相應的服務集合映射我已經做了,這裏只是省略。

現在,我希望我的屬性上的控制器操作的水平這樣使用:

[RoleAuthorize("DefaultPolicy", "CustomPermission")] 
public IActionResult List() 
{ 
} 

會有人建議我我將如何訪問處理程序RolePermissionAccessRequirement行動方法的頂部給出的權限屬性值 ??

我想根據Action方法之上的Authorize attribute中給出的自定義許可值執行某種訪問規則。

在此先感謝!

回答

0

要參數化自定義Authorize屬性,請創建一個實施IAsyncAuthorizationFilter的授權過濾器。然後將過濾器包裝在TypeFilterAttribute衍生的屬性中。該屬性可以接受參數並將其傳遞給授權過濾器的構造函數。

用例:

[AuthorizePermission(Permission.Foo, Permission.Bar)] 
public IActionResult Index() 
{ 
    return View(); 
} 

實現:

public class AuthorizePermissionAttribute : TypeFilterAttribute 
{ 
    public AuthorizePermissionAttribute(params Permission[] permissions) 
     : base(typeof(PermissionFilter)) 
    { 
     Arguments = new[] { new PermissionRequirement(permissions) }; 
     Order = Int32.MinValue; 
    } 
}  

public class PermissionFilter : Attribute, IAsyncAuthorizationFilter 
{ 
    private readonly IAuthorizationService _authService; 
    private readonly PermissionRequirement _requirement; 

    public PermissionFilter(
     IAuthorizationService authService, 
     PermissionRequirement requirement) 
    { 
     //you can inject dependencies via DI    
     _authService = authService; 

     //the requirement contains permissions you set in attribute above 
     //for example: Permission.Foo, Permission.Bar 
     _requirement = requirement; 
    } 

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context) 
    { 
     bool ok = await _authService.AuthorizeAsync(
      context.HttpContext.User, null, _requirement); 

     if (!ok) context.Result = new ChallengeResult(); 
    } 
} 

此外,登記DI一個PermissionHandler處理PermissionRequirement許可列表:

public class PermissionHandler : AuthorizationHandler<PermissionRequirement> 

看這個this GitHub上項目爲一個完整的考試PLE。

+0

@IIya謝謝你的真棒回答 –