📜  .net core authorizationhandlercontext - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:41.088000             🧑  作者: Mango

代码示例1
public class AccessToRouteHandler : AuthorizationHandler
    {
        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().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;
        }
    }