Alex Gordon
Alex Gordon

Reputation: 60691

simple web.config file question asp.net

i am using windows authentication with my asp.net application

different users will have different access to parts of the website.

i would like to do something like this in the config file:

    <appSettings>
     <role1>
<user>agordon</user><user>jsmith</user>
     </role1>
<role2><user>dtodd</user><user>kveel</user></role2>
    </appSettings>

is this possible to do?

when authenticating i would then get the username like this:

string username = HttpContext.Current.User.Identity.Name.ToString();

and check if that user exists in the specific role

Upvotes: 0

Views: 277

Answers (2)

John Saunders
John Saunders

Reputation: 161773

Use the <authorization> element:

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

You can then modify that for particular parts of your site:

<location path="Pages/Administration">
       <system.web>
          <authorization>
             <deny roles="*"/>
             <allow roles="Admin" />
          </authorization>
       </system.web>
</location>

Upvotes: 2

Russ Clarke
Russ Clarke

Reputation: 17909

You can do this, but it's really not the best way.

The problem here is that appSettings are not controlled by the Web.Config schema, so you'll need to programatically enumerate appSettings in a horrible fashion:

if (configurationSettings.HasKey("Role1")) { ... }
else if (configurationSettings.HasKey("Role2")) { ... }
else if (configurationSettings.HasKey("Role3")) { ... }
//continue ad.nauseum; it's not fun - trust me!

I know it's not what you're asking, but If you're using normal ASP.Net webforms then it's a little it of a slog; in each page/control you need to find out the current user and then determine if that user has access and then redirect or continue.

If you use ASP.Net MVC, it's a lot cleaner as you do this with attributes.

Authorize(Roles = "Managers")]
public ActionResult CompanySecrets()
{
    return View();
}

What the code there is doing, is saying If the user doesn't have the Managers role, don't give them access.

To provide an opposite example, here's a similar method using Web form (msdn example):

http://support.microsoft.com/kb/311495

Upvotes: 0

Related Questions