codybartfast
codybartfast

Reputation: 7543

Problem restricting anonymous access to an ASP.Net MVC Site

Whenever I restrict anonymous access in my MVC site I get a 404 error:

Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make > sure that it is spelled correctly.

Requested URL: /Account/Login

I've just been playing with MVC (RC1 Refresh) for the first time and after getting my exiting membership provider working I wanted to lock down the site to prevent anonymous access. I tried the traditional way using web.config with:

<configuration>
    <system.web> 
        <authorization> 
            <deny users="?"/> 
        </authorization> 
    </system.web> 
</configuration>

but got the above error even though I explicitly allowed anonymous access to the logon page.

I also tried the technique mentioned in Scott Gu's blog and secured the About page by adding the [Authorize] attribute in the HomeController

[Authorize]
public ActionResult About()
{
    return View();
}

but got the same error when I tried to access that page.

I've even tried a clean install on a separate machine.

So how do you enable Authorization in ASP.Net MVC RC1 Refresh?

Upvotes: 3

Views: 4594

Answers (2)

Rajat
Rajat

Reputation: 422

I would not suggest using forms authentication.

Instead use middleware pipeline.

public void ConfigureAuth(IAppBuilder app)
{
    // Enable the application to use a cookie to store information for the signed in user
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login")
    });
}

Ofcourse, you would need to remove the formsauthentication module from web config and use the [Authorize] keyword

Upvotes: 0

codybartfast
codybartfast

Reputation: 7543

The default Web.Config contains an error. It has:

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

This should be:

<authentication mode="Forms">
    <forms loginUrl="~/Account/LogOn"/>
</authentication>

(Excuse me asking and answering my own question but it took me ages to spot this and couldn't find any clues via Google or SO. if this has been posted before feel free to close).

Upvotes: 7

Related Questions