简体   繁体   中英

Override routing in ASP.NET CORE 2.2 to implicitly route to an area if user have some permissions

I'm looking for an easy way to change routing behaviour a little and add extra area data into route data if the user has some sorts of permissions.

Let's say for regular user url site/shop/12 should route to ShopController

but for admin it should route to AdminArea/ShopController


Please, consider that this question isn't about HTTP redirect, it's about extending infrastructure on a framework level to allow extra functionality on Routing or controller invocation

You could use URL Rewriting Middleware to redirect the request for Admin user

1.Create a Redirect rule:

public class RewriteRules
{
    public static void RedirectRequests(RewriteContext context)
    {
        //Your logic
        var IsAdminRole = context.HttpContext.User.IsInRole("Admin");
        if (IsAdminRole)
        {
            var request = context.HttpContext.Request;
            string area = "AdminArea";
            var path = request.Path.Value;

            //Add your conditions of redirecting
            if(path.Split("/")[1] != area)// If the url does not start with "/AdminArea"
            {
                context.HttpContext.Response.Redirect($"/{area}{ request.Path.Value }");
            }                          
        }
    }
}

2.Use the middleware in Startup Configure method:

app.UseAuthentication();//before the Rewriter middleware

app.UseRewriter(new RewriteOptions()
            .Add(RewriteRules.RedirectRequests)
            );

Add logic to the controller method that handles site/shop/12 to check if the user is an admin, and if it is, redirect to to the proper admin area and controller.

var isAdmin = IsUserAnAdmin();

if (isAdmin) {

    // This will redirect to the Index method defined in the ShopController
    // in the area name AdminArea
    return RedirectToAction("Index", "Shop", new { Area = "AdminArea" });

}

I think the best way is to set the correct URLs on the front-end and then validate the request on the end-point doing something like this:

        [HttpGet]
        [Route("v1.0/download/document")]
        public IActionResult download_document(int id, string token)
        {
            try
            {
                if (token == null || isNotAdmin(token))
                    return Unauthorized();

That way your end-points are protected and you avoid redirections. Plus, in my opinion everything makes a lot more sense on the front-end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM