14/5/12

Forms Authentication for a specific folder of your project

I post this mostly as a reminder to myself, just in case I need it again.
Today, one of the project's requirements was to deny access to unauthenticated user, in a specific folder of the web application. This folder contained reports generated by an SQL query, so general users should not be able to view them. The solution to the problem consisted of the following steps.

Create a new folder in the solution of my project and within it create a page that would host the reports and a custom login page.

In the Web config file of my project I added the following tag sections
  <location path="FOLDER NAME">
    <system.web>
   <authorization>
        <deny users="?"/>
     </authorization>
  </system.web>
 </location> 

in which I specify that this folder will deny access to unathendicated users and

    <authentication mode="Forms">
      <forms name="login" loginUrl="FOLDER NAME/lLOGIN PAGE.aspx" defaultUrl="REPORT PAGE.aspx" protection="All" path="/" timeout="30" />
    </authentication>

in which I specify that for this folder I will be using Forms authentication, in such a way that if am unauthenticated user tries to access the report page, he/she will be redirected to the custom login page and after a successfull login he/she will be redirected to the REPORT PAGE automatically.

Finally, in the code behind file of my LOGIN PAGE, in the login button click event I added the following code to use the Forms authentication method.

                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.ContentId.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, "");
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(faCookie);
                Response.Redirect(Request.RawUrl);


In conclusion, I could probably use a session object to store the authenticated user's credentials and check if the session is null or not in the page load event of the REPORT PAGE. In contrast, I was able to achieve the same result using Forms authentication, with less coding, which is always better... :)

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου