How does an MVC app know where to redirect the user when using the [Authorize] attribute?

414 Views Asked by At

If you setup an MVC app with authentication and use the [Authorize] tag, it will automatically redirect unauthenticated users to the login view.

But how does it know that page is the login page? I've looked through a example app, but couldn't find anything obvious.

edit

I forgot to mention that I'm using MVC6.

2

There are 2 best solutions below

2
On

You might find it in your web.config, in

<configuration>
    <system.web>
        <authentication mode="Forms">
            <forms loginUrl="~/Login" name=".ASPXFORMSAUTH" timeout="1440" />
        </authentication>
    </system.web>
</configuration>

Further reading: Jon Galloway: Looking at how the ASP.NET MVC Authorize interacts with ASP.NET Forms Authorization

2
On

Depending on the template you used to create your app, if you look in the App_Start folder, there is a file called Startup.Auth.cs. The code in there sets up the authentication. This is the code from the default MVC template:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an 
        //external login to your account.  
        OnValidateIdentity = SecurityStampValidator
            .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user
                    .GenerateUserIdentityAsync(manager))
    }
});