Unexpected "OPTIONS" method from Redirectresult - c#

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

Related

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());
}

Custom authorize attribute doesn't work after deploying to IIS

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.

Handling 'A potentially dangerous Request.Form value was detected from the client' and informing user of this error

i'm trying to handle the following issue
'A potentially dangerous Request.Form value was detected from the
client'
However, I can't find a good tutorial which explains how to catch this error and handle it. Just to be clear I want to stop users from entering any sort of markup when filling out my form. Most of the articles dealing with this issue suggest turning off request validation. This is not something I want to do. I want to catch the error and playback the error to the user. Any help would be greatly appreciated.
You can catch the error with an exception filter. Something like:
public class RequestValidationExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if(filterContext.Exception is HttpRequestValidationException)
{
filterContext.Result = new RedirectResult("/Error");
filterContext.ExceptionHandled = true;
}
}
}
You can get some more info in the Message of the exception, e.g.:
A potentially dangerous Request.QueryString value was detected from the client (FilterName="<script>alert("!!")<...").
But that is not really something to be shown to the user. So best thing to do would be a redirect to some generic error page. Or you can send them back to the current page.
I was doing some quick testing just now, and for some reason action filters and exception filters were not getting executed for me when the validation exception was happening - so I whipped up something quick using Application_Error(). (you can create this method in Global.asax.cs if it does not already exist)
protected void Application_Error()
{
var lastError = Server.GetLastError() as HttpRequestValidationException;
if (lastError == null)
return;
MvcHandler mvcHandler = Context.CurrentHandler as MvcHandler;
if (mvcHandler == null)
return;
RequestContext requestContext = mvcHandler.RequestContext;
if (requestContext == null)
return;
Server.ClearError();
Response.Clear();
Response.TrySkipIisCustomErrors = true;
// pick one of the following two options, or maybe more?
RedirectToUrl(requestContext);
ExecuteActionResult(requestContext, ...);
}
void ExecuteActionResult(RequestContext requestContext, ActionResult result)
{
string controllerName = requestContext.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
result.ExecuteResult(controllerContext);
}
void RedirectToUrl(RequestContext requestContext)
{
requestContext.HttpContext.Server.TransferRequest($"~/Error/Something", false);
}
I included an example of how to redirect to an arbitrary url, and also an example of how to execute a new ActionResult against the same controller that the original request was executed on.

MVC routing to Index if no action found in controller?

I have a multi-page form in my application, and as such, each method posts to the next. This works fine unless you try to visit the URL of one the methods decorated with [HttpPost].
Is there any way I can route all 404 requests within this specific controller to the Index method?
I will post this as an answer because I am not able to add it as comment
have a look to this link, it might help you
The idea you can catch the error in the OnActionExecuting and there you can make redirect
also as mentioned in this page in the answer, you can handle the Controller.OnException
public class BaseController: Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// Bail if we can't do anything; app will crash.
if (filterContext == null)
return;
// since we're handling this, log to elmah
var ex = filterContext.Exception ?? new Exception("No further information exists.");
LogException(ex);
filterContext.ExceptionHandled = true;
var data = new ErrorPresentation
{
ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
TheException = ex,
ShowMessage = !(filterContext.Exception == null),
ShowLink = false
};
filterContext.Result = View("Index", data); // to redirect to the index page
}
}
after this you can let all your controller to inhert from BaseController

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;

Categories