How to prevent anonymous users from accessing a file using forms authentication?

吃可爱长大的小学妹 提交于 2021-02-10 14:50:20

问题


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?


回答1:


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>



回答2:


a very simple approach is to use IIS to prevent anonymous access to a folder. just open IIS, select your site and select the folder which you want to secure it. after selecting the folder, double click on Authentication (in IIS section) in the Authentication page disable Anonymous Authentication. By now only your site authenticated users can access to your selected folder.



来源:https://stackoverflow.com/questions/9837846/how-to-prevent-anonymous-users-from-accessing-a-file-using-forms-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!