views:

26

answers:

1

I'm using my own database and forms authentication.

The database contains one table with users and second one with roles, that users are assigned to.

The question is: how to prepare the section in web.config, so it allows acces to the folder only for users belonging to one of the roles?

Second question: Using IIS configuration I can block direct access to all folders in the web directory. Let's say, that one of pages will contain links allowing to download files from those protected folders. If user is allowed to acces that site will he also be able to download that content?

+1  A: 

Here is a sample web.config, if you placed this file within a folder (within the structure of your web project) where you only want to allow users with the "Admin" Role (for example) this will do the job.

<?xml version="1.0"?>

<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
       <authorization>
          <allow roles="Admin"/>
          <deny users="*"/>
       </authorization>
    </system.web>
</configuration>

In order to link this to your security, after a successful login check you need to create a FormsAuthenticationTicket and pass in details like the user name and user roles.

A simple example showing this is:

 FormsAuthenticationTicket myTicket = new FormsAuthenticationTicket(1, myUserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, myUserRole, FormsAuthentication.FormsCookiePath);
 string hash = FormsAuthentication.Encrypt(myTicket);
 HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
 Response.Cookies.Add(myCookie);

That way you can do this in your code:

 if (Context.User.IsInRole("Admin")) {
      // Do Something
 } else {
      // Do Something Else
 }

And your Web.config file will work as I detailed above.

More info on FormsAuthenticationTickets here http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx

Simon Mark Smith
I know. But there is a problem, that the roles, that user is assigned to, are stored in my own database/table. Is there a way to connect somehow that table with web.config?
Charly
Answer modified to include more details as requested
Simon Mark Smith
I'm already using cookie authentication. But, correct me if I'm wrong: web.config in element "<allow roles="">" uses data stored in cookie in element myUserRole?
Charly