Forms Authentication & authorization MVC 4

孤街醉人 提交于 2019-12-19 06:19:12

问题


I'm trying to create an anonymous controller in order to acheive form authentication. I configured my IIS 7 with anonymous and form authentication enabled and set my web.config to deny anonymous users. On the login controller I put the [AllowAnonymous] decoration on my controller (and my actions).

The only action I can get on this set of configuration is the login action (which returns the "login" view), and I'm guessing that the MVC allows me to get this action because I set it as the login URL on my web.config.

Here is my web config configuration:

     <authentication mode="Forms">
        <forms loginUrl="~/Login/Login" timeout="2880" />
     </authentication>

All the other actions are redirected to the login action. On this set of configuration I can't achieve other important actions like restore password, register, etc.

What am I doing wrong?


回答1:


Use global authentification filter with custom behaviour instead of authorization configuration in web.config (best for MVC)

add global filter

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AuthorizeAttribute());
    }
}

Then, [AllowAnonymous] will works, and all other controllers and actions requires Authorization.




回答2:


You can also register Authorize filter in RegisterGlobalFilters method:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new AuthorizeAttribute());
} 

And then use the AllowAnonymous attribute on action methods that require anonymous access:

[Authorize]
public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult RecoverPassword()
    {
     ...
    }
}



回答3:


There are two possible approaches.

First - you can deny anonymous requests globally with the Authorize attribute and mark these few which do not need authorization with AllowAnonymous attribute (which is new to MVC4).

Second - do not deny globally but rather secure your selected controllers/actions with Authorize attribute.




回答4:


Did you try to allow the anonymous authorization for the URL's like in the sample below

<location path="Login/Login">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

Similar to this you should be setting for the ResetPassword / Restore password / Register etc...




回答5:


I removed the following portion from web.config then it is started working for me.

<!--<authorization>
  <deny users="?" />
</authorization>-->


来源:https://stackoverflow.com/questions/16382950/forms-authentication-authorization-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!