Forms authentication on MVC always redirects to logon
I have forms authentication on my MVC site and the default route is set to send users to /home/index. Home/index is excluded from the login requirement, via a Web.config location section. if I type in http://Example/home/index, I go to the home page as expected, but if I just do http://Example, I get redirected to the logon page.
If I turn off authentication and do http://Example, the default route works fine, and I'm sent to the home page.
Why is authentication not respecting the default route? Thanks!开发者_StackOverflow社区
You shouldn't be using the <location>
element in web.config
to handle authorization in an ASP.NET MVC application as it might clash with your routes. This is used in standard WebForms applications but it is considered bad practice in MVC.
The recommended way to handle this is to decorate your controllers/actions with the [AuthorizeAttribute]
. So get rid of all location
elements in web.config and decorate.
For me, the problem was the MachineKey
. It's required to decrypt/encrypt the cookie if you are doing that (for example: a web farm). Because the app couldn't decrypt the cookie, even though it was getting passed back and forth, the app acted like the cookie wasn't even there. Adding this setting to web.config fixed it for me:
<machineKey compatibilityMode="Framework20SP2" validationKey="some_hard_coded_long_key" decryptionKey="another_hard_coded_long_key" validation="SHA1" />
See this article for more on the machinekey.
精彩评论