Problem restricting anonymous access to an ASP.Net MVC Site

ε祈祈猫儿з 提交于 2020-01-04 05:07:12

问题


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?


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/548603/problem-restricting-anonymous-access-to-an-asp-net-mvc-site

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