Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-2.1

How do I restrict all access to a given route in .Net Core 2.1?


In my .Net Core 2.1 application, controllers are defined as

[Route("v1/api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class AccountController : Controller
{
    // peace & love
}

I need to deny access for all users to any route that matches the pattern

v1/api/operations/*

In Startup, we add MvcCore as

        services.AddMvcCore()
            .AddAuthorization()
            .AddApiExplorer();

and then configure the app to use MVC as

        app.UseMvc();

How can I ensure that no users can access any resource on the /operations route?


Solution

  • How can I ensure that no users can access any resource on the /operations route?

    Using IActionFilter middleware you could achieve that:

    RoutingRestrictionMiddleware:

    public class RoutingRestrictionMiddleware : IActionFilter
    {
    
        public void OnActionExecuting(ActionExecutingContext context)
        {
    
            if (context.HttpContext.Request.Path.StartsWithSegments("/api/Operations"))
            {
    
                context.Result = new JsonResult(new { HttpStatusCode.Unauthorized });
    
            }
    
    
        }
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
    
        }
    }
    

    Point to remember: "context.HttpContext.Request.Path.StartsWithSegments("/api/Operations") - here you can set the route you would like to restrict.

    Startup.cs:

       services.AddMvc(config =>
            {
                config.Filters.Add(new RoutingRestrictionMiddleware());
            });
    

    Controller Without Route Restriction:

        [Route("api/[controller]")]
        [ApiController]
        
        public class OperationsController : ControllerBase
        {
            
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "kiron", "farid" };
            }
        }
    }
    

    Output:

    enter image description here

    Controller With Route Restriction:

        [Route("api/[controller]")]
        [ApiController]
        
        public class OperationsController : ControllerBase
        {
            
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "kiron", "farid" };
            }
        }
    }
    

    Route Restriction Output:

    enter image description here