How to easily redirect if not authenticated in MVC 3?

前端 未结 4 618
夕颜
夕颜 2021-01-01 14:00

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 th

相关标签:
4条回答
  • 2021-01-01 14:04

    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>
    
    0 讨论(0)
  • 2021-01-01 14:10

    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).

    0 讨论(0)
  • 2021-01-01 14:13

    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

    0 讨论(0)
  • 2021-01-01 14:14

    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);
     }
    
    0 讨论(0)
提交回复
热议问题