Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone

I want to implement Httphandler to secure my documents in my website configured in iis 8.0 windows 8. So that no one can download the files without signing in the website. So in my Httphandler i check that if the session exist or not, if the session exit then allow the user to download the file otherwise redirect him to the login page.

The settings in my config file are as under.

<system.webServer>
       <handlers>
      <add name="Files" type="SecureFileHandler.FileHandler" verb="*" path="*.pdf" />
        </handlers>
<system.webServer>    


My HttpHandler is as under

C#
using System;
using System.Web;
using System.Web.SessionState;

namespace 
{
    public class FileHandler : IHttpHandler, IReadOnlySessionState
    {
       

        public bool IsReusable
        {
           
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (CheckWetherTheRequestForFileExistOrNot(context))
            {

                if (CheckUsersForFileDownloading(context))
                    context.Response.Redirect("~/index.aspx");
                            

            }
        }
        public bool CheckWetherTheRequestForFileExistOrNot(HttpContext context)
        {

            string url = context.Request.RawUrl.ToLower().Trim();
            if (url.Contains(".pdf"))
                return true;
            else
                return false;
        }

        public bool CheckUsersForFileDownloading(HttpContext context)
        {
            return (context.Session["FrontHiddenID"] == null) && (context.Session["HiddenID"] == null);
        }


    }
}



It is not working, neither it redirects nor it downloads the file.

Any advice and help regarding this issue is higly appreciated

Regards
Posted
Updated 15-Jan-13 8:29am
v3
Comments
ZurdoDev 15-Jan-13 14:23pm    
Where does it give that error? Also, you could just use Forms Authentication.
TanzeelurRehman 15-Jan-13 14:25pm    
Thank you for your response
Does forms authentication secure my files too
P_Dash 15-Jan-13 15:20pm    
See what result you are trying to achieve could be easily achieved using Forms Authentication.
Just make an Extra folder, name it as per your conveyance & implement Forms Authentication for this folder.

If you know forms authentication, you could easily do it.
But if you don't know how exactly to do it, then let me know & I'll post the Process Step wise here as a Solution.
TanzeelurRehman 16-Jan-13 1:13am    
Thanks
I have two type of users one is for front end and one for the admin end, In this httphandler i have to check both of them, if one of the session exist (front end user or admin user)then allow him to download the file otherwise redirect him to login page. Can we implement this scenario in form authentication, (e,g The form authentication should allow if any of the user either front or admin exist. otherwise redirect it to login page) if so pleas guide me.
P_Dash 16-Jan-13 4:33am    
Yes Forms Authentication surely can do what you want.
Basically you want to allow Downloading to the the users who are logged in to your site, it might be normal user/admin.

So basically to download PDF files every user need to Log In.
So for this As I said Create a Folder & Place all your PDF files in this folder.
Add a web.config to this folder & write code for authorization in it.

Now whenever an user logging in to your site store his identity in a Session variable & whenever any user wants to Download that PDF file check for the Session variable & if present then allow the user to download the file, if not redirect him to login page.

Basically redirecting to login page will be done by Form Authentication.You just need to check if Session Expired or not.

I know it looks like a bit complected, but believe me it's quiet easy to implement.

Let me know if you got it or not.

Your Handler is not right.

First, you will need to set the content header of the file to allow recognition of its mime type.

You could do something like the following (if you had forms authentication):

C#
 public void ProcessRequest(HttpContext context)
  {
if (context.User.Identity.IsAuthenticated)
    {
      string filename = context.Request.QueryString["File"];
      //Validate the file name and make sure it is one that the user may access
      context.Response.Buffer = true;
      context.Response.Clear();
      context.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
      context.Response.ContentType = "octet/stream";

// or "application/pdf"

      context.Response.WriteFile("~/App_Data/" + filename);
    }
}
 
Share this answer
 
Is your handler supposed to redirect when FrontHiddenID and HiddenID are null? If so I think you are succeeding there. If not, one of those two fields might have a value which would fail your check.

Also, your handler doesn't actually send the pdf to the user. If you don't have that in code somewhere else, you will need to add the download code here. Here is an example of how to enable downloading of a file.

http://blogs.msdn.com/b/nikhiln/archive/2008/05/22/httphandler-to-authorize-file-downloads-c-code-sample.aspx[^]
 
Share this answer
 
v2
As Per Your Request, Here I'm posting the whole thing right from the Starting of adding Web.config.

Step-1: Place a 'login.aspx' form in your Application & Write the Following code in it under Sign In button:
C#
protected void Button1_Click(object sender, EventArgs e)
{
    //Write your Logic for validating user as per your requirement.

    //Here I'm Defining a Session Variable for HiddenID Session.
    //You can define FrontHiddenID Session also as per your conveyance
    Session["HiddenID"] = true;
}


Step-2: Now I'm going to check whether Session variable exists or not when user is clicking Download Link. Here I'm using a Button for implementing Download logic:
C#
protected void Button1_Click(object sender, EventArgs e)
{
    //Checking if Session variable available or not
    if (Session["HiddenID"] != null || Session["FrontHiddenID"] != null)
    {
        //Mention the Filename user want to Download here
        string fileName = <provide your filename here>;
        //Logic for Providing download link to user 
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.TransmitFile(Server.MapPath("~/Doc/" + fileName));
        Response.End();
    }
    //If Session variable isn't available then Redirecting the user to login page
    else
        Response.Redirect("login.aspx");
}


I guess this should work for you.
Checked in my System & Works fine for me.

Let me know if it's working for you or not.
 
Share this answer
 
v3
Comments
TanzeelurRehman 17-Jan-13 0:02am    
Thank you for your great time,
Stay Blessed

Regards
TanzeelurRehman
P_Dash 17-Jan-13 1:04am    
No Probs Dear.
Actually I found this technique is more easier than Authorization, so Provided you with this.

Authorization way is also available, but this'd be easier to implement.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900