21

I am brand new to ASP.NET, and I'm trying to find a way to easily redirect an unauthenticated user from any page on the site to the logon page. I would prefer to not put the following code in every HTTP GET function if there is another option.

if (!Request.IsAuthenticated)
{
     return RedirectToAction("LogOn", "Account");
}
blachniet
  • 4,323
  • 5
  • 33
  • 34

4 Answers4

33

Mark your controller with [Authorize] attribute http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

See your web.config, by default you should have Forms authentication turned on authentication mode="Forms" http://msdn.microsoft.com/en-us/library/eeyk640h.aspx

Also look at this question ASP.NET MVC Authorization

In case if you want to have custom Authorize behavior look here Customizing authorization in ASP.NET MVC

Community
  • 1
  • 1
angularrocks.com
  • 26,767
  • 13
  • 87
  • 104
16

You can put the [Authorize] attribute over each action that needs to be authenticated.

Also, make sure that this section is defined in your Web.Config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
  • 2
    Exactly right, and just to clarify - this config section should be placed within "system.web". – tltjr May 27 '15 at 16:40
3

I just tried this:

<!-- using custom auth with MVC redirect -->
<authentication mode="None">
  <forms loginUrl="~/Home/Index"/>
</authentication>

and it still works, although I'm using custom auth. Not sure about timeout though - will [Authorize] still use the default one for Forms Auth or it won't manage timeouts at all (preferred behavior for custom auth).

JustAMartin
  • 13,165
  • 18
  • 99
  • 183
0

I used the below code snippet and found it to be very elegant not requiring to write any redirect statements. MVC takes care of the redirection based on the forms login page configuration and upon successfull login/registration, the user is sent back to the initial requested page

 if (!User.Identity.IsAuthenticated)
 {
    //return new HttpUnauthorizedResult(); //This or the below statement should redirect the user to forms login page
    return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
 }
Krishna
  • 2,451
  • 1
  • 26
  • 31