Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

.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;
        }
    }
Comment

PREVIOUS NEXT
Code Example
Csharp :: make an object disappear from a c# script unity 
Csharp :: how to check is object by this type c# 
Csharp :: how to check if control key is pressed c# 
Csharp :: C# check if is first run 
Csharp :: how to split list by date c# 
Csharp :: how to set a objects position to the mouse unity 
Csharp :: how to convert iformfile to byte array c# 
Csharp :: ldap check user exists 
Csharp :: c# list join 
Csharp :: change textbox text color c# 
Csharp :: how to reference function in unity 
Csharp :: c# override index operator 
Csharp :: C# How to change the text colour? 
Csharp :: C# datetime.now to string only numbers 
Csharp :: csharp check if env is development 
Csharp :: json get request c# 
Csharp :: c# datetimepicker set weeks after today 
Csharp :: lat long data type c# 
Csharp :: excute bash and other linux scripts from c# 
Csharp :: c# datetime to timestamp 
Csharp :: how to make an object invisible unity 
Csharp :: is keyboard clicked in Unity 
Csharp :: round float c# 
Csharp :: unity deltatime 
Csharp :: c# split on multiple characters 
Csharp :: button size xamarin 
Csharp :: asp net c# compare date to current 
Csharp :: untiy instanciate prefab 
Csharp :: cannot convert from string to type T 
Csharp :: c# making a folder wpf 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =