Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can mvc return Unauthorized code without redirecting to LogIn view

Tags:

My MVC web application serves two types of users.

  • First one over standard web browser;
  • Second one over REST returning only JSON data.

Additionally,

  • Both require Authentication and authorization;
  • Both scenarios are differentiated based on the route so that I know what content to serve.

When users access the application, if they are not logged in, the application should react differently.

  1. In the first case it should return the default LogIn page (this is fine).
  2. In the second case it should return a 401 Unauthorized code only.

I'm used to working with WCF REST service where I could raise an exception like this:

throw new WebProtocolException(System.Net.HttpStatusCode.Unauthorized, exc.Message, exc); 

and receive a 401 message. The problem with the same approach within MVC when I put the statusCode like this:

HttpContext.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized 

it always redirects to the LogIn page.

How can I do this?

I've tried overriding the AuthorizeAttribute and handling the OnAuthorization function, but still as soon as I set the statusCode to 401 it gets redirected to the LogIn page.

like image 734
mateo Avatar asked Sep 10 '10 19:09

mateo


People also ask

How does MVC authorize work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.

How MVC authorization is implemented?

Authorization in MVC is controlled through the AuthorizeAttribute attribute and its various parameters. At its simplest applying the AuthorizeAttribute attribute to a controller or action limits access to the controller or action to any authenticated user.

How redirect a specific view from controller in MVC?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.


1 Answers

To prevent login page redirection you must set SuppressFormsAuthenticationRedirect property of HttpContext.Response to true;

 HttpContext.Response.SuppressFormsAuthenticationRedirect = true; 
like image 107
Kambiz Shahim Avatar answered Oct 31 '22 17:10

Kambiz Shahim