Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms Authentication & authorization MVC 4

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?

like image 948
Shahar Avatar asked May 05 '13 08:05

Shahar


2 Answers

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.

like image 82
hVostt Avatar answered Oct 12 '22 17:10

hVostt


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()
    {
     ...
    }
}
like image 25
Kamyar Avatar answered Oct 12 '22 16:10

Kamyar