Custom authorize attribute doesn't work after deploying to IIS - c#

I have overridden the HandleUnauthorizedRequest method in my asp.net mvc application to ensure it sends a 401 response to unauthorized ajax calls instead of redirecting to login page. This works perfectly fine when I run it locally, but my overridden method doesn't get called once I deploy to IIS. The debug point doesn't hit my method at all and straight away gets redirected to the login page.
This is my code:
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
filterContext.Result = new JsonResult
{
Data = new
{
success = false,
resultMessage = "Errors"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
base.HandleUnauthorizedRequest(filterContext);
}
else
{
var url = HttpContext.Current.Request.Url.AbsoluteUri;
url = HttpUtility.UrlEncode(url);
filterContext.Result = new RedirectResult(ConfigurationManager.AppSettings["LoginUrl"] + "?ReturnUrl=" + url);
}
}
}
and I have the attribute [AjaxAuthorize] declared on top of my controller. What could be different once it's deployed to IIS?
Update:
Here's how I'm testing, it's very simple, doesn't even matter whether it's an ajax request or a simple page refresh after the login session has expired -
I deploy the site onto my local IIS
Login to the website, go to the home page - "/Home"
Right click on the "Logout" link, "Open in a new tab" - This ensures that the home page is still open on the current tab while
the session is logged out.
Refresh Home page. Now here, the debug point should hit my overridden HandleUnauthorizedRequest method and go through the
if/else condition and then redirect me to login page. But it
doesn't! it just simply redirects to login page straight away. I'm
thinking it's not even considering my custom authorize attribute.
When I run the site from visual studio however, everything works fine, the control enters the debug point in my overridden method and goes through the if/else condition.

When you deploy your web site to IIS, it will run under IIS integrated mode by default. This is usually the best option. But it also means that the HTTP request/response model isn't completely initialized during the authorization check. I suspect this is causing IsAjaxRequest() to always return false when your application is hosted on IIS.
Also, the default HandleUnauthorizedRequest implementation looks like this:
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
filterContext.Result = new HttpUnauthorizedResult();
}
Effectively, by calling base.HandleUnauthorizedRequest(context) you are overwriting the JsonResult instance that you are setting with the default HttpUnauthorizedResult instance.
There is a reason why these are called filters. They are meant for filtering requests that go into a piece of logic, not for actually executing that piece of logic. The handler (ActionResult derived class) is supposed to do the work.
To accomplish this, you need to build a separate handler so the logic that the filter executes waits until after HttpContext is fully initialized.
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new AjaxHandler();
}
}
public class AjaxHandler : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
var httpContext = context.HttpContext;
var request = httpContext.Request;
var response = httpContext.Response;
if (request.IsAjaxRequest())
{
response.StatusCode = (int)HttpStatusCode.Unauthorized;
this.Data = new
{
success = false,
resultMessage = "Errors"
};
this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.ExecuteResult(context);
}
else
{
var url = request.Url.AbsoluteUri;
url = HttpUtility.UrlEncode(url);
url = ConfigurationManager.AppSettings["LoginUrl"] + "?ReturnUrl=" + url;
var redirectResult = new RedirectResult(url);
redirectResult.ExecuteResult(context);
}
}
}
NOTE: The above code is untested. But this should get you moving in the right direction.

Related

Unexpected "OPTIONS" method from Redirectresult

In my MVC-Application I have my own error handling that catches different errors. If an authentication error occurs it redirects to a loginpage:
public class JsonExceptionAttribute : HandleErrorAttribute {
if (filterContext.Exception.Message == "Auth expired") {
public override void OnException(ExceptionContext filterContext) {
string newUrl = Logic.GetUrl());
filterContext.Result = new RedirectResult(newUrl, false);
filterContext.ExceptionHandled = true;
return;
}
}
}
GetUrl() returns a valid Url.
This seems to work fine most of the time. It always returns a 302 redirect that will then call the new URL as a GET request.
But this does not work everywhere. If the Exception is thrown in my AuthorizeAttribute the 302 is still returned, but the Browser tries to open the Url with the httpmethod "OPTIONS" instead of GET causing an error:
If I take the exact url and copy/paste it into the browser (so making a GET from it) it works fine. So where is this "OPTIONS" coming from all of a sudden?
This happens in different browsers and the result is the same when I return the Redirect in the HandleUnauthorizedRequest in the AuthorizeAttribute instead of doing this in the HandleErrorAttribute

Redirect to the same page with flash message in AuthorizeAttribute

So I have two custom authorize attributes: 1) is to redirect the user to login whenever a session has expired or not authenticated; 2) is currently in progress.
The idea for the second custom authorize attribute is to redirect the user to the same page before he/she navigated to the next page or prevent from redirecting to the next page request. Let say the code is
public class CustomAuth2Attribute : AuthorizeAttribute
{
private const string _errorController = "Error";
public override void OnAuthorization(AuthorizationContext filterContext)
{
var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var action = filterContext.ActionDescriptor.ActionName;
var area = "";
if (filterContext.RouteData.DataTokens.ContainsKey("area"))
area = filterContext.RouteData.DataTokens["area"].ToString();
if (controller == _errorController)
{
return;
}
// checking the user identity whether the user is allowed to access this page
// then redirect to the previous page before this request and add flash note: "not allowed to access the content"
}
}
The idea is if the user do not have access to a certain page I do not flag this as not authorize instead I should be returning them to the page they were before with the note message.
Also tried the below code:
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller,
action,
area
}));
I'm getting too many redirects which is because I'm referencing the current controller, action, and area instead of the previous one. I also tried getting the UrlReferrer value but this is always null.
Any way I can achieve this? Any help is appreciated. Thank you in advance.
You can override HandleUnauthorizedResult for that:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.ToString());
}

Cookies suggestion (ideas) for the EU General Data Protection Regulation (GDPR)

The EU General Data Protection Regulation (GDPR) will come into effect from 25th May 2018. One can read in detail here. This time it has to be all opt-in and they have very heavy fine (€20 million or 4% of global earning!).
Since, it has to be all opt-in(at least in our case), we have decided user accepts our cookies to receive our services.
We will not be logging out current users to give us concept, however, we will present them consent page when they come into one of our sites. If they say yes then we will save an "accept-cookie" or else they won't be able to come into our sites. Afterwards, whenever a use logs into our site, we check the existence of this cookie.
My idea in implementing this solution is to intercept the user request and check the existence of accept-cookie and redirect to the requested resource or controller in our case as we will asp.net mvc accordingly.
My question is can I do this using RegisterRoutes to route request to a controller and if yes, redirect to the requested controller?
What about this solution? Though, the solution is for different aspect. I have modified the variables name from language to consent to make it more meaningful(not trying to copy):
public class EnsureLanguagePreferenceAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var euCookie = filterContext.HttpContext.Request.Cookies["ConsentCookies"];
if (euCookie == null)
{
// cookie doesn't exist, redirect use to a View showing
//all the cookies being saved in client machine
// and to take user consent(accept or deny)
}
// do something with euCookie
base.OnActionExecuting(filterContext);
}
}
As this rule comes into effect on 25th May 2018, it would be nice to hear your idea regarding different kind of implementation.
Finally, I came up with something that I wanted--intercepting user request and redirecting based upon a certain cookie. This can be used as a nuget as we have multiple applications and saving cookies could be done from one of the application. As it is made as an action filter attribute, it can be place above controller:
[MyAcceptCookieCheck]
public class HomeController : Controller
This makes it easy to implement across all application and operations regarding saving cookies will be done from the one of the application so that it will be easy to make any changes i.e., only from one place.
public class MyAcceptCookieCheck : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var cookies = filterContext.HttpContext.Request.Cookies["OurAcceptCookie"];
var values = filterContext.RouteData.Values.Values;
originalRequest = filterContext.HttpContext.Request.Url.AbsoluteUri;
RouteValueDictionary requestOrigin = new RouteValueDictionary { {
"url", originalRequest } };
if (cookies == null && !values.Contains("CookieConsent")) //so that it won't loop endlessly
{
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
//filterContext.Result = new RedirectResult(urlHelper.Action("CookieConsent", "Home"));
filterContext.Result = new RedirectResult(urlHelper.Action("CookieConsent","Cookie",requestOrigin ,"https","www.my-domain.com/mysitename"));
}
else if(cookies != null)
{
string controllerName = filterContext.RouteData.Values["controller"].ToString();
string actionName = filterContext.RouteData.Values["action"].ToString();
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.Result = new RedirectResult(urlHelper.AbsolutePath(actionName, controllerName));
}
}
}
Code for AbsolutePath (courtesy):
public static string AbsolutePath(this UrlHelper url, string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
Now, I can redirect all requests without having that particular cookie to a cookie consent page and show user all the details about cookies being used and ask for permission to save "ConsentCookie".

Custom authorize attribute only works on localhost

I have a custom authorize attribute used for Ajax requests:
public class AjaxAuthorize : AuthorizeAttribute {
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
UrlHelper urlHelper;
if (filterContext.HttpContext.Request.IsAjaxRequest()) {
urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.HttpContext.Response.StatusCode = 401;
//Return JSON which tells the client where the login page exists if the user wants to authenticate.
filterContext.HttpContext.Response.Write(new JavaScriptSerializer().Serialize(
new {
LoginUrl = string.Format("{0}?ReturnURL={1}", FormsAuthentication.LoginUrl, urlHelper.Encode(filterContext.HttpContext.Request.Url.PathAndQuery))
}
));
filterContext.HttpContext.Response.End();
} else {
base.HandleUnauthorizedRequest(filterContext);
}
}
}
When I run the application locally I get the JSON result back from the Ajax request. However, when I put the code on my beta server I end up getting the IIS 401 HTML response.
Does anyone see something wrong with my code that would make this work only on localhost? Additionally, if anyone has a better idea for returning the JSON result I am open to that as well.
There is some strange power of StackOverflow that results in the OP thinking through the question differently after posting. I'll leave my answer here in hopes that it might benefit someone else.
It just occurred to me that IIS7 was getting in the way. I fixed this by adding one line of code:
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

Redirect users with suspended accounts without creating redirect loop

I have a subscription based MVC 2 application with the basic .NET Membership service in place (underneath some custom components to manage the account/subscription, etc). Users whose accounts have lapsed, or who have manually suspended their accounts, need to be able to get to a single view in the system that manages the status of their account. The controller driving that view is protected using the [Authorize] attribute.
I want to ensure that no other views in the system can be accessed until the user has re-activated their account. In my base controller (from which all my protected controllers derive) I tried modifying the OnActionExecuting method to intercept the action, check for a suspended account, and if it's suspended, redirect to the single view that manages the account status. But this puts me in an infinite loop. When the new action is hit, OnActionExecuting gets called again, and the cycle keeps going.
I don't really want to extend the [Authorize] attribute, but can if need be.
Any other thoughts on how to do this at the controller level?
EDIT: in the base controller, I was managing the redirect (that subsequently created the redirect loop) by modifying the filterContext.Result property, setting it to the RedirectToAction result of my view in question. I noticed everytime the loop occurs, filterContext.Result == null. Perhaps I should be checking against a different part of filterContext?
Ok, so here's my solution in case it helps anyone else. There's got to be a more elegant way to do this, and I'm all ears if anyone has a better idea.
In my BaseController.cs:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewData["CurrentUser"] = CurrentUser; // this is a public property in the BaseController
if (CurrentUser != null && CurrentUser.Account.Status != AccountStatus.Active)
{
// if the account is disabled and they are authenticated, we need to allow them
// to get to the account settings screen where they can re-activate, as well as the logoff
// action. Everything else should be disabled.
string[] actionWhiteList = new string[] {
Url.Action("Edit", "AccountSettings", new { id = CurrentUser.Account.Id, section = "billing" }),
Url.Action("Logoff", "Account")
};
var allowAccess = false;
foreach (string url in actionWhiteList)
{
// compare each of the whitelisted paths to the raw url from the Request context.
if (url == filterContext.HttpContext.Request.RawUrl)
{
allowAccess = true;
break;
}
}
if (!allowAccess)
{
filterContext.Result = RedirectToAction("Edit", "AccountSettings", new { id = CurrentUser.Account.Id, section = "billing" });
}
}
base.OnActionExecuting(filterContext);
}

Categories