We are using forms authentication to authenticate users. In our application there is a page to download an exe.
When I am debugging the code in visual studio, it allows only logged-in users to download the file. When other users try to download the file, they are automatically redirected to the login page.
But when I am running this from a virtual directory, all users (whether logged-in or not) can download the file by accessing the direct path like http://testappln/foldername/test.exe
.
How to prevent accessing of unauthorized users in this situation?
One possibility is to put the file inside the App_Data
folder which is forbidden direct access to and then have a generic ASHX handler to read the contents of the file and return it to the client. Then you could restrict the access to this generic handler to only authenticated users:
<%@ WebHandler Language="C#" Class="Download" %>
using System;
using System.Web;
public class Download : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "application/octet-stream";
context.Response.WriteFile("~/App_Data/test.exe");
}
public bool IsReusable
{
get
{
return false;
}
}
}
and in your web.config you restrict the access to the Download.ashx
handler:
<location path="Download.ashx">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>