ASP.NET Core MVC-基于资源的授权HandleRequirementAsync调试

时间:2018-07-28 14:46:53

标签: asp.net asp.net-core authorization asp.net-core-2.0 asp.net-core-identity

我实现了自己的csr(基于资源的授权) 与文档类似。

  

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.0&tabs=aspnetcore2x

我的代码:

AuthorizationHandler
  

IsOwnerRequirement类

 public class UserRUDPermissionHandler : AuthorizationHandler<IsOwnerRequirement, DataAccess.Entities.User>
        {
            private readonly IAuthenticationService authenticationService;

            public UserRUDPermissionHandler(IAuthenticationService authenticationService)
            {
                this.authenticationService = authenticationService;
            }

            protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, IsOwnerRequirement requirement, DataAccess.Entities.User resource)
            {
                DataAccess.Entities.User currentUserDb = await authenticationService.GetUserAsync(context.User);

                if (context.User.IsInRole("Admin") || resource.Id == currentUserDb.Id)
                {
                    context.Succeed(requirement);
                    return;
                }

                context.Fail();
            }
        }
  

启动文件

public class IsOwnerRequirement : IAuthorizationRequirement
{
}
  

控制器

    services.AddAuthorization(options =>
            {
                options.AddPolicy("RUDPolicy", policy =>
                policy.Requirements.Add(new IsOwnerRequirement()));
            });

  services.AddScoped<IAuthorizationHandler, UserRUDPermissionHandler>();

但是我重定向到

  

http://localhost:51129/Account/AccessDenied?ReturnUrl=%2FUser%2FEdit

因此,我假设 [Authorize(Policy = "RUDPolicy")] [HttpGet] public IActionResult Edit(Guid id)... 返回失败。有什么方法可以调试UserRUDPermissionHandler?我尝试在  AuthorizationHandler,但它并没有在断点处停止。

0 个答案:

没有答案