Pergunta

I'm building an ASP.NET MVC web application and I'm trying to restrict access to pages.

I've specified that I want to use forms authentication in my Web.config:

<system.web>
    ...
    <authentication mode="Forms">
        <forms loginUrl="~/login" timeout="20" protection="All" />
    </authentication>
    <authorization>
        <deny users="?" />
    </authorization>
    ...
</system.web>

This will deny access to all pages, but I want to make some pages public. I can do this in Web.config as well:

<location path="about-us">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>
<location path="contact-us">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>
…

This works all fine. The problem is the start page, more precisely when the user goes to "http://www.mydomain.com/", with no further path specified. How can I specify that this page should be public?

I've tried some variations, but nothings seems to work. I always get an error:

No path

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

Empty path

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

Dot

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

Slash

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

Any suggestions?

Foi útil?

Solução

You don't need to manage authentication in your web.config for MVC. Trying using the [Authorize] attribute on your Controller classes and methods:

[Authorize] // everything here requires auth
public class AdminController()
{
    public ActionResult Dashboard() { ... }
}

public class ReportController()
{
    [Authorize] // only this method requires auth
    public ActionResult SecretReport() { ... }

    public View PublicReport() { ... }
}

// everything here is accessible
public class HomeController()
{
    public ActionResult Index() { ... }

    public ActionResult AboutUs() { ... }

    public ActionResult ContactUs() { ... }
}

In ASP.NET MVC you can use [AllowAnonymous] which allows you to do exactly that on a specific method

Outras dicas

The start page just your default Controller that you provide in RouteConfig. So if you are using the default values you need to allow acces to HomeController and the Index() method. When working with MVC and authorization I find this very valuable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top