Joe Enos
Joe Enos

Reputation: 40393

ASP.NET authentication to allow/prevent page access and show/hide link at the same time

I'm looking for a way to easily wrap security around a location, while at the same time using that to show/hide links on my menu.

I know how to block the location for unauthorized users, like:

<location path="AdminDirectory">
    <system.web>
        <authorization>
            <allow roles="SomeRole"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

And I can show/hide links with code, like:

myLink.Visible = User.IsInRole("SomeRole");

But what I'm looking for is a way to do this so that the "SomeRole" role name only has to be configured once. If I could read from the location element and test it in code, that would be ideal, but I'm not seeing a way to do that.

// Something like:
myLink.Visible = TestLocationAccess("AdminDirectory");

I can think of a really crappy way of doing this with a javascript/AJAX call to "test" the directory from the client and show/hide the link with javascript, but obviously that's not ideal.

Thanks

Upvotes: 3

Views: 3884

Answers (2)

Crab Bucket
Crab Bucket

Reputation: 6277

Consider using ASP.Net sitemap It has functionality built in to show or hide links based on roles

i.e within the source xml for the site map it is possible to define the roles that the links apply to i.e.

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="default.aspx" title="Home">
        <siteMapNode url="admin.aspx" title="Admin" roles="Admin" />
        <siteMapNode url="user.aspx" title="User Page" roles="User" />
    </siteMapNode>
</siteMap>

You could use roles to limit access in the web.config and use the same roles to limit the navigation in the site map.

I guess you are still controlling the authorisation in two places. It's what I would do (have done in the past). Don't know if that gets you to where you need to be going.

Anyway here's Scott Guthrie explaining better than I can

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the CheckUrlAccessForPrincipal method:

myLink.Visible = UrlAuthorizationModule
    .CheckUrlAccessForPrincipal("~/AdminDirectory", User, "GET");

Since the method is static you obviously need to pass as second argument an instance of the current IPrincipal.

Upvotes: 4

Related Questions