How to easily redirect if not authenticated in MVC 3?
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.
开发者_JAVA技巧if (!Request.IsAuthenticated)
{
return RedirectToAction("LogOn", "Account");
}
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
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>
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).
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);
}
精彩评论