Authorize login URL in asp.net MVC 3

2019-04-29 00:03发布

问题:

I am working on an Asp.Net MVC 3 application. I have created admin area for the website and applied [Authorized] attribute to actionmethods after login. When I try to access these urls directly without login like admin/home or admin/productlist, I am redirected to /Home/Login with authentication error. I want to redirect to Admin/Login.

Please suggest. Thanks

回答1:

The login URL for ASP.NET applications (including MVC3 ones) is controlled in web.config, in the forms authentication section:

<configuration>
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="2880" />
    </authentication>
  </system.web>
</configuration>

The trick for you is that you want two different login URLs. ASP.NET has a great feature where you can have a web.config file in each directory of your project, and as needed it will use the most specific setting it can find, up to the root web.config. So in the folder where you have your admin views ("Admin" I'm guessing), you should be able to create a second web.config, which will apply only to those pages and lower in the tree:

<configuration>
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Admin/Login" timeout="2880" />
    </authentication>
  </system.web>
</configuration>


回答2:

If this is a Stock MVC 3 Authorization then myself as well as many others have had problems with the incorrect url address being set for the "LogOn" Action... For some reason authorize is trying to send a user to Account\Login and looking at the account views tells that there is actually no "Login" view it is called "LogOn" so you have to fix this in the Web.config file with the following:

                <add key="loginUrl" value="~/Account/LogOn" />


回答3:

You can override your Authorize action filter to handle those issues. For example, you can check not only roles, but some specific permissions, and redirect to different Url's. And also using this approach can take into account your routing configuration.
Take a look at this answer : asp.net mvc Adding to the AUTHORIZE attribute