Change request path in action filter in ASP.NET Core

4.5k views Asked by At

We have an action filter, ActionAuthorizationFilterAttribute, that performs some authorization tests (getting its permissions from the session, more on that later) in its OnActionExecuting method, and if the tests are ok, it just returns, and if not, it sets ForbidResult on the context's Result property. So far so good. But we have one case, where the session retruns null for the permissions after some idle time period, and we need to set the request path to "/", instead of the user doing that by hand, so for example if the user is trying to access some url after his session ends, like http://mydomain/mywebapp/someurl, the method should return him to http://mydomain/mywebapp/, and the application will start its session init stuff again. This works when the does this by hand, but it doen't work in the method. Here's the code for the method:

public override void OnActionExecuting(ActionExecutingContext context)
    {
        var path = context.HttpContext.Request.Path.Value.Trim().ToLower();
        var session = context.HttpContext.Session;
        var permittedUrls = session.GetJson<List<string>>(SesstionStateKeys.PermittedUrls);

        if (permittedUrls == null)
        {
            context.HttpContext.Request.Path = "/";
            return;
        }

        if (permittedUrls.Any(url => path.Contains(url.Trim().ToLower())))
        {
            return;
        }

        context.Result = new ForbidResult(); //new UnauthorizedResult();

        base.OnActionExecuting(context);
    }
2

There are 2 answers

1
ivamax9 On
public override void OnActionExecuting(ActionExecutingContext context)
{
   var path = context.HttpContext.Request.Path.Value.Trim().ToLower();
   var session = context.HttpContext.Session;
   var permittedUrls = session.GetJson<List<string>>(SesstionStateKeys.PermittedUrls);

   if (permittedUrls == null)
   {
      context.Result = new RedirectResult("your_url");
      return;
   }

   if (permittedUrls.Any(url => path.Contains(url.Trim().ToLower())))
   {
      return;
   }

   context.Result = new ForbidResult(); //new UnauthorizedResult();

   base.OnActionExecuting(context);
}
2
Dmitry On

Changing Path in code will not redirect user to new path. You should return RedirectResult if you want user to be redirected to index/login page.

For API best option is return UnauthorizedResult.