.net core authorizationhandlercontext

96

.net core authorizationhandlercontext -

    public class AccessToRouteHandler : AuthorizationHandler<AccessToRouteRequirement>
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly DbContext dbContext;

        public AccessToRouteHandler(IHttpContextAccessor httpContextAccessor, DbContext dbContext)
        {
            this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
            this.dbContext = dbContext;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessToRouteRequirement requirement)
        {
            var filterContext = context.Resource as AuthorizationFilterContext;
            var routeInfo = context.Resource as RouteEndpoint;
            var response = filterContext?.HttpContext.Response;

            if (!context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(context.User.Identity.Name))
            {
                response?.OnStarting(async () =>
                {
                    filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                });

                context.Fail();
                return Task.CompletedTask;
            }

            var verb = this.httpContextAccessor.HttpContext.Request.Method;
            var routeKey = string.Empty;

            if (context.Resource is Endpoint endpoint)
            {
                var cad = endpoint.Metadata.OfType<ControllerActionDescriptor>().FirstOrDefault();

                var controllerFullName = cad.ControllerTypeInfo.FullName;
                var actionName = cad.ActionName;
                var bindings = cad.Parameters;
                var actionParams = ".";

                if (bindings.Any())
                {
                    bindings.ToList().ForEach(p => actionParams += p.ParameterType.Name + ".");
                }

                routeKey = $"{controllerFullName}.{actionName}{actionParams}{verb}";
            }

            var route = dbContext.Routes
                .Include(t => t.Roles)
                .FirstOrDefault(r => r.RouteKey == routeKey);

            if (route != null && route.Roles.Any(role => context.User.HasClaim(c => c.Value == role)))
            {
                // user belong to a role associated to the route.
                context.Succeed(requirement);
                return Task.CompletedTask;
            }

            response?.OnStarting(async () =>
            {
                filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
            });

            context.Fail();
            return Task.CompletedTask;
        }
    }

Comments

Submit
0 Comments