locked
Protect Folder Asp.net RRS feed

  • Question

  • User-1324173748 posted

    Asslam-o-Alaikum

    I have create a web Application in which user put there Basic information with one Picture etc...

    I save the Picture name only in DataBase and the images are in the ImageFolder.

    But when i upload a my Application i saw that if enter the ImageFolder Name in url it open all the images Name & open easily with out Login the user.

    I Want to make the ImageFolder Secure in a way that it can't be access 

    What can i do for that if You know Please let me know a Way........

    Thanks.......

    Wednesday, January 19, 2011 11:49 PM

Answers

  • User713056278 posted

    Hi,

    i am not using iis Create Build/Publish website & upload it Live on testing url using CuteFtp......
     

    For my experience ,you can create an HttpHandler to protect files and folders.Then add the HttpHandler to web.config file of your web application.

    I would like to suggest you to check the link below for the sample which describes how to protect files and folders using HttpHandlers, in VB.NET and C#.

    http://www.codeproject.com/KB/web-security/HttpHandlersInAspNet.aspx

    Hope it can help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 31, 2011 5:42 AM

All replies

  • User-821857111 posted

    Put the folder outside of the root of the web site and use a Handler: http://www.mikesdotnetting.com/Article/122/Simple-File-Download-Protection-with-ASP.NET or if you are hosted on IIS 7 in Integrated mode, you can just map a handler to specific file tpyes and prevent browsing that way: http://www.blackbeltcoder.com/Articles/asp/writing-a-custom-http-handler-in-asp-net



    Thursday, January 20, 2011 12:20 AM
  • User-1364446067 posted

    WalikumSalam Taha.

    Put your images in App_Data folder. It is a protected folder by Asp.net. Second, jsut as Mike's blog post says Use HttpHandler (.ashx) so that your file could be served as well from App_Data.

    Thanks

    --

    Hope it helps.

    Thursday, January 20, 2011 12:32 AM
  • User-1324173748 posted

    Thank for ur Reply if i put my images folder in App Data folder than why i use httpHandlers please define me the difference between them Thanks.

    Thursday, January 20, 2011 1:42 AM
  • User-1324173748 posted

    After Put my Image Folder in App_Data and change the Path of image

    Profile Images/22.jpg 
    to
    App_Data/Profile Images/22.jpg

    But it not Work Please Help ........

    Thursday, January 20, 2011 2:09 AM
  • User-2139489267 posted


    After Put my Image Folder in App_Data and change the Path of image

    Profile Images/22.jpg 
    to
    App_Data/Profile Images/22.jpg

    But it not Work Please Help ........

    Are you still able to download the file without login?

    Thursday, January 20, 2011 2:28 AM
  • User-1364446067 posted

    Thank for ur Reply if i put my images folder in App Data folder than why i use httpHandlers please define me the difference between them Thanks.

    Its because file will not be served if its in App_Data. So u need a handler to serve that file to user from App_Data. You can use the code Mike gae u in his blog post.

    Just for testing' place an image give the ImageUrl' path to any image in App_Data on the design time. Run the project and u will not see the image still, Because its in App_Data folder. so thats where u need a Handler (.ashx) to serve that file.


    --

    Hope it helps..


    Thursday, January 20, 2011 2:33 AM
  • User-1324173748 posted

    Yes i am able to download file with out login like that

    http://localhost:3930/ICMAP/Profile Images

    and it show me all images on that folder with out Login

    Thursday, January 20, 2011 2:51 AM
  • User-2139489267 posted

    http://localhost:3930/ICMAP/Profile Images

    But this is not in App_Data

    and you must have set directory browsing in IIS.

    Thursday, January 20, 2011 2:55 AM
  • User-821857111 posted

    if i put my images folder in App Data folder than why i use httpHandlers please define me the difference between them

    Your question would be answered if you actually read the first article I linked to.


    Thursday, January 20, 2011 3:00 AM
  • User-2139489267 posted

    Your question would be answered if you actually read the first article I linked to

    Yes I do agree with Mike :)


    Thursday, January 20, 2011 3:05 AM
  • User-1364446067 posted

    Yes i am able to download file with out login like that

    http://localhost:3930/ICMAP/Profile Images


    I recommended you to put ur images in App_Data not in other folder (ICMAP/Profile Images in your case). Plus I'd also recommend you to go through Mike's article once. It will help you building the Handler too


    --

    Hope this helps



    Thursday, January 20, 2011 3:54 AM
  • User-1324173748 posted

    I am really sorry to tell you that Mike i can't understand your Code. I have a Folder Name ImageFolder on Directory, in which all images are placed

    If some one know the Folder name than he directly access ImageFolder from URL like http://localhost:3930/ICMAP/ImageFolder .

    My user is currently login with my existing data base so no need to Re-login them again. either user Login or Not. I want that he never access ImageFolder .

    If Possible Please define me with coding, either i place image folder or not, Please explain me with coding

    I am confuse with your code...

    Thank u v.Much

    Thursday, January 20, 2011 4:21 AM
  • User-1364446067 posted

    Hi. Actually Mike has used Forms Authentication thats why you confused it with your authentication.

    I exaplain you in steps..

    1. First put your application folder 'ImageFolder' in App_Data folder of the application.

    If you are uploading any file in ImageFolder from your application then you should also update that code which uploads files to ImageFodler. You should now upload them all in App_Data/ImageFolder.


    2. Add to your project a Generic Handler (Default name is Handler1.ashx)

    3. I suppose you have a session in which u store your logged in user name. This session will be empty/ null in case user accesses the file from URL without being logged in.

    Now, In that handler you can see a method "ProcessRequest". You can write something like this in that method (code is from Mike's blog with an if updated only)

    public void ProcessRequest(HttpContext context)
      {
        if (context.Session["UserID"] != null)
        {
          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";
    
          context.Response.WriteFile("~/App_Data/" + filename);
        }
      }
    
    

    4. You can place this on the page to have user access the file

    <a href="Handler1.ashx?File=HelloWorld.txt">Click Here to Get File</a>


    --

    Hope this helps.. Or you can ask more and more always..





    Thursday, January 20, 2011 4:43 AM
  • User-1324173748 posted

    Thank you for Your Reply i am now clear with your Points 

    Thanks....

    But the my goal is image not a text.txt File, still i am not acheive a image URL..

    Thanks again

    <a href="Handler1.ashx?File=HelloWorld.txt">Click Here to Get File</a>

    Thursday, January 20, 2011 5:37 AM
  • User-1324173748 posted

    After look you code i update my code know my code seems to be like that.


    public void ProcessRequest (HttpContext context)
        {
            if (context.Session["Reg_No"] != null)
            {
                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";
                context.Response.WriteFile("~/App_Data/Profile Images/" + filename);
            }
        }



    And try to Get URL of image using


    string str = ("Handler1.ashx? File = " + imgName + "");


    But i get "Handler1.ashx? File = 22.jpg"  

    I need to some thing like that "App_data/ImageFolder/22.jpg"

    i ' m new For Asp Http Handlers thats why Problem create for me 

    Please help me As Soon As Possible.................................. :(


    Thursday, January 20, 2011 5:58 AM
  • User-1364446067 posted

    Hi Taha.

    When you do

    string filename = context.Request.QueryString["File"];

    then the filename does contains "22.jpg".

    Now you can write this line of code: context.Response.WriteFile("~/App_Data/ImageFolder/" + filename);

    "~/App_Data/ImageFolder/" + filename   does contain  your file.


    --

    Hope this helps..






    Thursday, January 20, 2011 9:43 AM
  • User-1324173748 posted

    I do the same thing but nothing happend

    if (context.Session["Reg_No"] != null)

            {

                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";

                context.Response.WriteFile("~/App_Data/Profile Images/" + filename);

            }


    Friday, January 21, 2011 5:49 AM
  • User-2139489267 posted

    Please check the filename by debugging, are you getting value or null?


    Friday, January 21, 2011 5:53 AM
  • User-1364446067 posted

    context.Response.WriteFile("~/App_Data/Profile Images/" + filename);


    Are u sure this is the path where you placed your images. Wasn't it "ImageFolder" before instead of Profile Images?

    You can also check this while debugging this block. Hit the thread again then.


    --

    Hope this helps..

    Friday, January 21, 2011 8:01 AM
  • User713056278 posted

    Hi,

    I save the Picture name only in DataBase and the images are in the ImageFolder.

    But when i upload a my Application i saw that if enter the ImageFolder Name in url it open all the images Name & open easily with out Login the user.

    I Want to make the ImageFolder Secure in a way that it can't be access

     

    According to your description ,for my experience ,you can use Application_BeginRequest method in global.asax file to check whether the URL of page is typed by user and make a judgment that if the extension value of  page's url  is .gif or .jpg (and so on) .,then let user know the image file is not allowed to access to.

    In this way ,you can avoid user who is not login trying to type the URL and access the image file.

    Here is the sample:

    1.Create the table which used to store records in database like this:

    PermissionForFile tabel

    ID

    filepath

    filename

    UserID

    user put there Basic information with one Picture etc...

    2.When the user uploads a image file ,insert a record to the table in database.

    3.Use a page to show the records,suppose the page named as "filelist.aspx".

    4.Here is the code.

    Code in Global.asax:

     void Application_BeginRequest(object sender, EventArgs e)
        {
            string path = HttpContext.Current.Request.Path;
            string[] path_Elements = path.Split('.');
            string ext = path_Elements[path_Elements.Length - 1];
            if (ext.ToLower() == "gif" || ext.ToLower() == "jpg")
            {
                if (!IsUrl())
                {
                    HttpContext.Current.Response.Redirect("~/NoPermission.aspx");
                }
            }
    
        }
        bool IsUrl()//The method is used to check whether the page is opend by typing the url in browser 
        {
            string str1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            string str2 = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            return ((str1 != null) && (str1.IndexOf(str2) == 7));
        }

    2.Code in NoPermission.aspx:

     

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        You have no permission to access the page(file) 
        <a href="filelist.aspx"> filelist.aspx</a>
        </div>
        </form>
    </body>
    </html>


    3.Code in filelist.aspx(the page is used to show the list of image files which belong to the current user):

    .aspx:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <%--Show the list of files base on the value in database after user login--%>
        </div>
        </form>
    </body>
    </html>


     

    .cs:

     protected void Page_Load(object sender, EventArgs e)
        {
            if (!CheckIsLogin())
            {
                Response.Redirect("Login.aspx");
            }
            else
           {
                // Use the UserName as UserID to get the records form PermissionForFile tabel
                // Display the records as you want.
           }
        }
        public bool CheckIsLogin()
        {
            // When user login,please set value to Session["User"].
            // for example:Session["User"] = UserName;
            if (Session["User"] != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    either user Login or Not. I want that he never access ImageFolder .

    I would like to suggest you to modify the code in Application_BeginRequest method as below:

    void Application_BeginRequest(object sender, EventArgs e)
        {
            string path = HttpContext.Current.Request.Path;
            
            // Change the name of folder as your own
            string foldername = "ImageFolder";
            if (path.Contains(foldername))
            {
                HttpContext.Current.Response.Redirect("~/NoPermission.aspx");
            }
    
        }


     

    Please check the links below for the similar threads which provide some solutions for the same issue:

    http://forums.asp.net/p/1611551/4124520.aspx

    http://forums.asp.net/p/1610459/4125252.aspx#4125252

    http://forums.asp.net/p/1622251/4168410.aspx

    Hope it can help you.

    Tuesday, January 25, 2011 1:06 AM
  • User-1324173748 posted

    Ming Xu - MSFT Thanks for your Reply ...

    I have the second problem is that i call images from

    string foldername = "Profile Images";

            if (path.Contains(foldername))

            {

                Response.Redirect("~/NoPermission.aspx");

            }

    in my home Page i.e. that is not display now due to the Path contains 'foldername'

    Tuesday, January 25, 2011 4:34 AM
  • User-1324173748 posted

    i am successful to secure my folder but the another problem comes is that the Page1.aspx can not access the the imageFolder & not show image.

    by that check 

    if (path.Contains(foldername))

            {

                Response.Redirect("~/NoPermission.aspx");

            }


    Page1.aspx can not access the image.....

    Please help me as soon as Possible

    Tuesday, January 25, 2011 5:32 AM
  • User713056278 posted

    Hi,

    Page1.aspx can not access the image.....

    Please help me as soon as Possible

     

    According to your description ,I would like to suggest you to modify the code which contained in Application_BeginRequest method as below:

    Code in Global.asax file:

     void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now);   
            string path = HttpContext.Current.Request.Path;
    
            // Change the name of folder as your own
            string foldername = "Profile Images";
            if (path.Contains(foldername) && !IsUrl())
            {
                HttpContext.Current.Response.Redirect("~/NoPermission.aspx");
            }
    
        }
        // The method is used to check whether the page is opend by typing the url in browser.    
        bool IsUrl()
        {
            string str1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            string str2 = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            return ((str1 != null) && (str1.IndexOf(str2) == 7));
        }  


     

    Hope it can help you.

    Tuesday, January 25, 2011 9:45 AM
  • User-1324173748 posted

    No its not work it show me all images in folder 


    Thursday, January 27, 2011 5:42 AM
  • User713056278 posted

    Hi,

    No its not work it show me all images in folder 
     

    Could you please provide more information about issue and what exactly are you trying to accomplish?If so ,we can provide further suggestions for you.

     

    Thursday, January 27, 2011 9:27 AM
  • User-1324173748 posted

    Yes sure.....

    I have a folder 'Profile Images' in which all images are upload by the user, example A Web Application in which user view/Update their profile Upload Picture..

    In my Web Application images are upload on folder & Image Name stored in dataBase

    The problem is that, if any one know the folder name 'Profile Images' and access it directly form the URL either he is Login or Logout he view all the images on the folder 'Profile Images' like that:

    http://localhost:3930/ICMAP/profile images/

    browser open all the images

    I want to Protect that folder.... only

    If you have any more questions Plz ask me...

    Thanks 

    Sunday, January 30, 2011 11:46 PM
  • User713056278 posted

    Hi,

    The problem is that, if any one know the folder name 'Profile Images' and access it directly form the URL either he is Login or Logout he view all the images on the folder 'Profile Images' like that:

    http://localhost:3930/ICMAP/profile images/

    browser open all the images

    I want to Protect that folder.... only

     

    According to your description ,as I mentioned in my previous reply you can modify the code which contained in Application_BeginRequest method as below:

    Code in Global.asax file:

     void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now);   
            string path = HttpContext.Current.Request.Path;
    
            // Change the name of folder as your own
            string foldername = "Profile Images";
    
            // Please make sure the condition is !IsUrl() here.
            if (path.Contains(foldername) && !IsUrl())
            {
                HttpContext.Current.Response.Redirect("~/NoPermission.aspx");
            }
    
        }
        // The method is used to check whether the page is opend by typing the url in browser.    
        bool IsUrl()
        {
            string str1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            string str2 = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            return ((str1 != null) && (str1.IndexOf(str2) == 7));
        }  


    No its not work it show me all images in folder 

    Could you please provide more information about the current code in your Global.asax file?If so ,we can find the issue more conveniently and provide further suggestions for you.

    Hope it can help you.

    Monday, January 31, 2011 12:41 AM
  • User-1324173748 posted

    Your this post is similar to previous post that i try but it not protect image folder & show all images using URL........

    That's the problem

    Monday, January 31, 2011 1:34 AM
  • User713056278 posted

    Hi,

    Actually ,the code works fine at my side. 

    Could you please provide more information about the current code in your Global.asax file?

    Monday, January 31, 2011 1:45 AM
  • User-1324173748 posted

    Yes sure.....


    void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now);
            string path = HttpContext.Current.Request.Path;
    
            string foldername = "Profile Images";
            if (path.Contains(foldername) && !IsUrl())
            {
                HttpContext.Current.Response.Redirect("~/NoPermission.aspx");
            }
        }
    
        bool IsUrl()
        {
            string str1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            string str2 = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            return ((str1 != null) && (str1.IndexOf(str2) == 7));
        }   

    if any more quest again plz tell me

    Monday, January 31, 2011 1:56 AM
  • User391373791 posted

    In IIS manager and remove at least anonymous access if not all access. Your application code can continue to use its contents but HTTP requests can not access it.

    Monday, January 31, 2011 2:29 AM
  • User391373791 posted

    In IIS manager and remove at least anonymous access if not all access. Your application code can continue to use its contents but HTTP requests can not access it.


    Monday, January 31, 2011 2:30 AM
  • User713056278 posted

    Hi,

    For my experience ,the issue may be related to you have deployed the site by using IIS without adding the handler mappings that handle responses for specific request types.

    If you deploy the website by using IIS 7. I would like to suggest you to follow the steps as below which used to add script map to Handler Mappings of your web application in IIS.

    1.Open the Internet Information Service(IIS) Manager.

    2.Select your web site application  ,in features view window ,please select Handler Mappings (double click) -> click Add Script Map in Action part which display at right side.

    3.Enter the information in Add Script Map pop up window :

    Request Path:*.jpg                       (input the extension of the image files as your own)

    Executable:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll       (the information at my side,if yours is not as the same as mine,please change it as your own)

    Name:Enter what you like

    4.Click the Request Restrictions button:

    In Verbs tag,select One of the follow verbs and enter GET,HEAD,POST,DEBUG

    In Access tag,please select Script

    5.Click ok

    6.Restart the web site.

    Then the web.config file of your web application will add the following code:

     <system.webServer>
            <handlers>
                <add name="images" path="*.jpg" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
            </handlers>

        </system.webServer>

    Hope it can help you.

    Monday, January 31, 2011 3:01 AM
  • User-1324173748 posted

    i am confuse here.... i am not using iis Create Build/Publish website & upload it Live on testing url using CuteFtp......

    Please tell me where i set iis option in that why

    Thanks

    Monday, January 31, 2011 5:20 AM
  • User713056278 posted

    Hi,

    i am not using iis Create Build/Publish website & upload it Live on testing url using CuteFtp......
     

    For my experience ,you can create an HttpHandler to protect files and folders.Then add the HttpHandler to web.config file of your web application.

    I would like to suggest you to check the link below for the sample which describes how to protect files and folders using HttpHandlers, in VB.NET and C#.

    http://www.codeproject.com/KB/web-security/HttpHandlersInAspNet.aspx

    Hope it can help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 31, 2011 5:42 AM