如何在视图中使用自定义授权属性

时间:2019-08-09 14:18:49

标签: c# asp.net-core authorization

我有一个这样的自定义授权属性。在控制器中工作。我有自己的权限表,该表与身份角色表具有多对多关系。我可以检入控制器,以便将指定的权限分配给像这样对用户进行身份验证的任何角色。

 [Permission("test")]
 public IActionResult Index()
        {
            return View();
        }

我也想在视图侧这样做。

尝试了很多类似这样的方法,但是所有方法都基于策略授权。

@if (await AuthorizationService.AuthorizeAsync(User, Model, "test"))
                    {
                    <a href="calendar.html" class="waves-effect">
                        <i class="ti-calendar"></i><span> Calendar</span>
                    </a>
                     ...
                     ...
                    }

这是“我的自定义”授权属性代码

public class PermissionAttribute : TypeFilterAttribute
{
    public PermissionAttribute(params string[] permission) : base(typeof(PermissionRequirementFilter))
    {
        Arguments = new object[] { permission };

    }
}

public class PermissionRequirementFilter : IAuthorizationFilter
{
    readonly string[] _permission;
    private readonly ApplicationDbContext _db;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger<ExternalLoginModel> _logger;

    public PermissionRequirementFilter(ApplicationDbContext db, UserManager<ApplicationUser> userManager, ILogger<ExternalLoginModel> logger, params string[] permission)
    {
        _db = db;
        _userManager = userManager;
        _logger = logger;
        _permission = permission;
    }


    public void OnAuthorization(AuthorizationFilterContext context)
    {

        if (!IsUserAuthenticated(context))
        {
            context.Result = new UnauthorizedResult();
            return;
        }


        // Get all the roles the user belongs to and check if any of the roles has the permission required
        // for the authorization to succeed.
        var id = _userManager.GetUserId(context.HttpContext.User);
        var user = _db.Users.Include(e => e.UserRoles)
            .ThenInclude(c => c.Role)
            .ThenInclude(c => c.Permissions)
            .ThenInclude(c => c.Permission)
            .FirstOrDefault(c => c.Id == id);
        if (user != null)
        {
            var userRole = user.UserRoles.Select(c => c.Role).ToList();
            var permissions = userRole.SelectMany(c => c.Permissions.Select(e => e.Permission.Label)).ToList();
            if (permissions.Any(c => _permission.Contains(c)))
            {
                _logger.LogInformation("succedd.");
                //context.Result = new AcResult();
                return;
            }
        }
        _db.Dispose();

        context.Result = new ForbidResult();
    }

0 个答案:

没有答案