1

I'm developing custom AuthorizeAttribute with MVC5. I want to check if user is allowed to access an action or not. on selection/click of a link system should check if user is authorized to access the link or not. In case user is not authorized then keep user on same view and display the authorization message in a popup.

public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        if (!IsOwner(filterContext))
        {
            filterContext.Controller.TempData["Authorisedmessage"] = "You do not have sufficient privileges for this operation.";
            var currentpageUrl = HttpContext.Current.Request.UrlReferrer;
filterContext.RequestContext.HttpContext.Response.Redirect(currentpageUrl.ToString(), true);
        }
    }

it keeps user on same page but gives error in @Html.AntiForgeryToken placed on the page.

what is to be done to cater this situation.

tereško
  • 58,060
  • 25
  • 98
  • 150
Brijesh
  • 369
  • 2
  • 10
  • Got the solution to get rid of "AntiForegryToken" - http://stackoverflow.com/questions/34270192/server-cannot-append-header-after-http-headers-have-been-sent-exception-at-html But now i cannot get the error message on Page/view loaded after "UrlReferrer" – Brijesh Feb 25 '16 at 12:07

1 Answers1

0

Solved it, it is kind of work around but it solved the issue.

IN OnAuthorization method, I parsed the HttpContext.Current.Request.UrlReferrer.LocalPath & manually created the route by assigning conroller name in routeValues. For example i've assigned controller name as routeValues["controller"] and similarly assigned the action & parameter values.

Code is as mentioned below:

filterContext.Controller.TempData["AuthorizationFailed"] = "You do not have sufficient privileges for this operation.";
string[] UrlFragment = HttpContext.Current.Request.UrlReferrer.LocalPath.Split('/');
var routeValues = new RouteValueDictionary();
routeValues["controller"] = UrlFragment[1];
string[] Action = UrlFragment[2].Split('?');
routeValues["action"] = Action[0];
if (Action.Length > 1)
{
  string[] Parameter = Action[1].Split('&');
  for (int i = 0; i < Parameter.Length; i++)
  {
    string[] splitted = Parameter[i].Split('=');
    routeValues[splitted[0]] = splitted[1];
  }
}
filterContext.Result = new RedirectToRouteResult(routeValues);

Now read the value from TempData["AuthorizationFailed"] to display the message. Thanks

Brijesh
  • 369
  • 2
  • 10