In Asp.Net MVC 2 is there a better way to return 401 status codes without getting an auth redirect - asp.net-mvc

I have a portion of my site that has a lightweight xml/json REST API. Most of my site is behind forms auth but only some of my API actions require authentication.
I have a custom AuthorizeAttribute for my API that I use to check for certain permissions and when it fails it results in a 401. All is good, except since I'm using forms auth, Asp.net conveniently converts that into a 302 redirect to my login page.
I've seen some previous questions that seem a bit hackish to either return a 403 instead or to put some logic in the global.asax protected void Application_EndRequest()
that will essentially convert 302 to 401 where it meets whatever criteria.
Previous Question
Previous Question 2
What I'm doing now is sort of like one of the questions, but instead of checking the Application_EndRequest() for a 302 I make my authorize attribute return 666 which indicates to me that I need to set this to a 401.
Here is my code:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS)
{
//check for 666 - status code of hidden 401
Context.Response.StatusCode = 401;
}
}
Even though this works, my question is there something in Asp.net MVC 2 that would prevent me from having to do this? Or, in general is there a better way? I would think this would come up a lot for anyone doing REST api's or just people that do ajax requests in their controllers. The last thing you want is to do a request and get the content of a login page instead of json.

How about decorating your controller/actions with a custom filter:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var user = filterContext.HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
}
}
and in your controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[RequiresAuthentication]
public ActionResult AuthenticatedIndex()
{
return View();
}
}

Another way of doing this is to implement a custom ActionResult. In my case, I wanted one anyway, since I wanted a simple way of sending data with custom headers and response codes (for a REST API.) I found the idea of doing a DelegatingActionResult and simply added to it a call to Response.End(). Here's the result:
public class DelegatingActionResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
Command(context);
// prevent ASP.Net from hijacking our headers
context.HttpContext.Response.End();
}
private readonly Action<ControllerContext> Command;
public DelegatingActionResult(Action<ControllerContext> command)
{
if (command == null)
throw new ArgumentNullException("command");
Command = command;
}
}

The simplest and cleanest solution I've found for this is to register a callback with the jQuery.ajaxSuccess() event and check for the "X-AspNetMvc-Version" response header.
Every jQuery Ajax request in my app is handled by Mvc so if the header is missing I know my request has been redirected to the login page, and I simply reload the page for a top-level redirect:
$(document).ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
// if request returns non MVC page reload because this means the user
// session has expired
var mvcHeaderName = "X-AspNetMvc-Version";
var mvcHeaderValue = XMLHttpRequest.getResponseHeader(mvcHeaderName);
if (!mvcHeaderValue) {
location.reload();
}
});
The page reload may cause some Javascript errors (depending on what you're doing with the Ajax response) but in most cases where debugging is off the user will never see these.
If you don't want to use the built-in header I'm sure you could easily add a custom one and follow the same pattern.

TurnOffTheRedirectionAtIIS
From MSDN, This article explains how to avoid the redirection of 401 responses : ).
Citing:
Using the IIS Manager, right-click the
WinLogin.aspx file, click Properties,
and then go to the Custom Errors tab
to Edit the various 401 errors and
assign a custom redirection.
Unfortunately, this redirection must
be a static fileā€”it will not process
an ASP.NET page. My solution is to
redirect to a static Redirect401.htm
file, with the full physical path,
which contains javascript, or a
meta-tag, to redirect to the real
ASP.NET logon form, named
WebLogin.aspx. Note that you lose the
original ReturnUrl in these
redirections, since the IIS error
redirection required a static html
file with nothing dynamic, so you will
have to handle this later.
Hope it helps you.

I'm still using the end request technique, so I thought I would make that the answer, but really
either of the options listed here are generally what I would say are the best answers so far.
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS)
{
//check for 666 - status code of hidden 401
Context.Response.StatusCode = 401;
}
}

Related

Error in MVC redirect: Server cannot append header after HTTP headers have been sent

I want to do a simple redirect when a user first loads the website.
For that, I just access the RouteData on BeginExecuteCore() method of BaseController and if URL does not have a specific value, then I will redirect to another https route:
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
// access route data
if (condition == true)
Response.Redirect(string.Format("https://{0}/en/en", Request.Url.Authority), true);
}
}
}
Some facts:
I achieve the result I want
I get the Exception "Server cannot append header after HTTP headers have been sent."
I've tried several alternatives: Using other methods to do the redirect like Initialize(RequestContext requestContext) etc
I tried to Use parameter EndResponse=true on Redirect method
I tried to clear the headers before doing the redirect
In all the previous experiments I got the same exception
I'm using MVC 5
My question is:
How can I redirect the user to another route in the most efficient way knowing that I need to have access to RouteData and without throwing the annoying exception?
Thank you!
Response.Redirect(anyUrl) cause 302 status code
And Html.AntiForgeryToken() has conflict with 302 status code normally.
You can put the following code in Application_Start:
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
Security Warning: SuppressXFrameOptionsHeader =true prevents your
site from being loaded into an iframe.
read more
I'm not familiair with the method BeginExecuteCore() as i am still working with mvc 3 and 4.
In mvc 4 i would use an action filter to check something before a page loads.
The reason why you are seeing that error is probably because you are to late redirecting the user as the page is already being loaded.
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (condition == true)
filterContext.Response.Redirect(string.Format("https://{0}/en/en", Request.Url.Authority), true);
}
}
Take a look at: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

MVC3: Session_Start Fires twice when testing for Roles

I need to do some authentication for a web app with MVC3. The customer would like there to be a generic page to show if they do not have any of the role groups in windows AD that are allowed to use the app. I found a pretty simple way to do it, but just curious if it is a valid way or if there is something better out there.
Basically in the Session_Start in the global I am checking for User.IsInRole() and if that returns false then I do a Response.Redirect(). This question is: after it his the code in the IF statement and hits the Response.Redirect() code then it hits the session one more time before it goes to the AccessDenied page in the root of the app. Is this okay? Will it cause any issues If they are valid and does not enter the If to do the response.redirect?
//if (!User.IsInRole("test_user"))
//{
// Response.Redirect("~/AccessDenied.aspx", true);
//}
I would recommend you to write your Authorization filter for MVC3 and do this type of logic there:
public class RoleFilter: AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext filterContext)
{
if (!User.IsInRole("test_user"))
{
filterContext.HttpContext.Response.StatusCode = 302;
filterContext.Result = new RedirectResult("~/AcessDenied.aspx");
}
}
}
Also I wouldn't recommend you to use Response.Redirect because it aborts current thread.

How to step out from https to http mode in asp.net mvc

I have made my Login page as Https enabled by adding the attribute [RequireSSL] on controller Action and it works fine. But after successful login it remains in https environment, however the page is non https page.
Can anybody give me workaround how to step out from https to http mode?
Any help in this regard will be greatly appreciated.
You basically need to do the opposite, which is have a [DoesNotRequireSSL] attribute, which effectively does the opposite of the {RequireSSL] attribute, i.e., redirect to http protocol
public class DoesNotRequireSSL: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
if (request.IsSecureConnection && !request.IsLocal)
{
string redirectUrl = request.Url.ToString().Replace("https:", "http:");
response.Redirect(redirectUrl);
}
base.OnActionExecuting(filterContext);
}
}
Also, if you would like to ensure that multiple pages have this behaviour, you can set up a base controller, from which all your non-http controllers can inherit from so you dont have to worry about having to repeat yourself for every page which needs this.
CAUTION: I had a similar question. One important thing I learnt was that your auth cookie will be sent over plain text after switching back to HTTP. See this.
CAUTION 2 : Don't forget to consider the dreaded You are about to be redirected to a connection that is not secure message
If you're writing a bank application you need to be real careful - and also realize the increasing number of users on public wifi connections that could well [esily] be funneled through some sneaky proxy. Probably a much bigger concern for mainstream sites but a concern for us all to be aware of.
See also my other question (no answers at time of writing - but then I only just asked it!)
I know this is quite an old question, but many of the links presented above are dead and this code addresses it for ASP.NET MVC 5 by making some slight modifications to the RequireHttpsAttribute that is included in the System.Web.Mvc namespace:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ForbidHttpsAttribute : FilterAttribute, IAuthorizationFilter
{
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.HttpContext.Request.IsSecureConnection)
{
HandleHttpsRequest(filterContext);
}
}
protected virtual void HandleHttpsRequest(AuthorizationContext filterContext)
{
// only redirect for GET requests, otherwise the browser might not propagate the verb and request
// body correctly.
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("The requested resource can only be accessed *without* SSL.");
}
// redirect to HTTP version of page
var url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url);
}
}
The code comes from this article, which briefly discusses some of the security concerns of forcing users to redirect from HTTPS to HTTP as well.

With ASP.NET membership, how can I show a 403?

By default, ASP.NET's membership provider redirects to a loginUrl when a user is not authorized to access a protected page.
Is there a way to display a custom 403 error page without redirecting the user?
I'd like to avoid sending users to the login page and having the ReturnUrl query string in the address bar.
I'm using MVC (and the Authorize attribute) if anyone has any MVC-specific advice.
Thanks!
I ended up just creating a custom Authorize class that returns my Forbidden view.
It works perfectly.
public class ForbiddenAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else
{
// auth failed, display 403 page
filterContext.HttpContext.Response.StatusCode = 403;
ViewResult forbiddenView = new ViewResult();
forbiddenView.ViewName = "Forbidden";
filterContext.Result = forbiddenView;
}
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}
Asp.net has had what I consider a bug in the formsauth handling of unauthenticated vs underauthenticated requests since 2.0.
After hacking around like everyone else for years I finally got fed up and fixed it. You may be able to use it out of the box but if not I am certain that with minor mods it will suit your needs.
be sure to report success or failure if you do decide to use it and I will update the article.
http://www.codeproject.com/Articles/39062/Salient-Web-Security-AccessControlModule.aspx

How to config Asp.net Mvc for redirecting every request to configuration page?

For Asp.net Mvc project, I need to redirect every request to configuration page when user(should be admin of this website) visit this website at the first time. This operation like default login page(every request will be redirect to default login page if access denied).
After user config the configuration file, Route table will be mapped to normal controllers.
Ps. This page should helps Admin for detect error configuration and easy to deploy.
Update #1
I try to use ASP.NET MVC WebFormRouting Demo on Codeplex. But I can't redirect when user visit some existing page like "~/AccessDenied.aspx" or "~/web.config".
routes.MapWebFormRoute("RedirectToConfig", "{*anything}", "~/App_Config");
Thanks,
From your description, this appears to be an authorization concern, so I would recommend a custom Authorize attribute class (inherit from AuthorizeAttribute).
From here you can override the OnAuthorization method where you can check if the user has completed your required configuration steps and set the filterContext.Result accordingly. A basic implementation would look something like this (this assumes you have a valid /Account/Configure route):
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
var user = ; // get your user object
if(user.IsConfigured == false) // example
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{
"ConfigureUserRoute",
filterContext.RouteData.Values["ConfigureUserRoute"]
},
{"controller", "Account"},
{"action", "Configure"}
});
return;
}
}
}
You can find other examples of how to create a custom AuthorizeAttribute class here on StackOverflow.
2 ideas:
Use a catch-all rule on top of your routing table and put a constraint on it that checks for the config status
Put the code for this check in Application_BeginRequest in GlobalAsax
Details for the catch-all idea:
Create a rule with url "{*path}" and put it first in your list
Create a constraint to activate this rule only in case the configuration is not done yet
Create a simple controller e.g. ConfigController with a single action that does nothing but a RedirectToUrl("config.aspx")
But the solution in Application_BeginRequest would be simpler, since the whole code to handle this in one place
Now, I can apply technique from my another question to solve this problem. By keep some value in static instance when application is starting. Please look at the following code.
partial ConfigBootstapper.cs
public class ConfigBootstapper
{
public static EnableRedirectToConfigManager = false;
}
partial ConfigModule.cs
void HttpApplication_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (ConfigBootstapper.EnableRedirectToConfigManager)
{
app.Response.Redirect("~/App_Config");
}
}
partial Global.asax
protected void Application_Start()
{
[logic for setting ConfigBootstapper.EnableRedirectToConfigManager value]
}
PS. Don't forget to checking some condition that cause infinite-loop before redirect.

Resources