Home > Back-end >  How do I restrict all access to a given route in .Net Core 2.1?
How do I restrict all access to a given route in .Net Core 2.1?

Time:05-20

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?

CodePudding user response:

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

Using IActionFilter middleware you could achive 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)
    {

    }
}

Note:

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

Hope that would guided you accordingly

  • Related