停止在asp.net中未经授权的文件下载

本文关键字:授权 文件下载 asp net | 更新日期: 2023-09-27 18:27:17

我有一个login.aspx页面,其中包含用于用户名和密码的自定义文本框,即没有loginview
在提供正确的用户名和密码后,我分配了一个sessionid,用于访问网站上的其他页面。

现在要下载file (1234),我将用户重定向到~/download.aspx?fileid=1234,在该页面上,我检查会话id并将用户发送到文件url,即~/file/1234.pdf
如果有人直接输入文件url,那么我无法阻止他
请指导我怎么做。。。

附言:我在web.config文件中读到了关于authentication rule的内容,但不知道如何将用户标记为已验证用户——他在登录时提供了正确的用户名和密码。(我只是从数据库中检查用户名和密码,并重定向到主页)

停止在asp.net中未经授权的文件下载

您的身份验证策略相当弱。您应该将站点的区域(即本例中的文件目录)与角色绑定,并将用户分配给它们。

然而,为了解决更直接的问题,只需禁止外部世界访问files目录,当他们点击~/download.aspx?fileid=1234时,只需为他们提供文件。您可以在这里找到相关说明:如何正确地提供PDF文件

看看这个-http://support.microsoft.com/kb/301240

在那篇文章的第4点"对事件处理程序进行编码,使其验证用户凭据"中,它解释了如何在验证用户后设置身份验证cookie

要查看的代码:

FormsAuthenticationTicket tkt;
      string cookiestr;
      HttpCookie ck;
      tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, 
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
      cookiestr = FormsAuthentication.Encrypt(tkt);
      ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
      if (chkPersistCookie.Checked)
      ck.Expires=tkt.Expiration;    
            ck.Path = FormsAuthentication.FormsCookiePath; 
      Response.Cookies.Add(ck);

你能做的是:

1. Enable form authentication in web.config
2. deny anonymous access to downloads folder
3. When user authenticates, set authentication cookie and redirect user to download folder
4. download folder now can only be accessed by logged in user and id

下面是我在项目中使用的代码

void ServeFile(string fname, bool forceDownload)
{
 if(UserHasPermission(fname))
 {
  DownloadFile(fname,forceDownload);
 }
 else
 {
  ShowMessage("You have no permission");
 }
}
private void DownloadFile( string fname, bool forceDownload )
{
  string path = MapPath( fname );
  string name = Path.GetFileName( path );
  string ext = Path.GetExtension( path );
  string type = "";
  // set known types based on file extension  
  if ( ext != null )
  {
    switch( ext.ToLower() )
    {
    case ".htm":
    case ".html":
      type = "text/HTML";
      break;
    case ".txt":
      type = "text/plain";
      break;
    case ".doc":
    case ".rtf":
      type = "Application/msword";
      break;
    case ".pdf":
      type = "Application/pdf";
      break;
    }
  }
  if ( forceDownload )
  {
    Response.AppendHeader( "content-disposition",
        "attachment; filename=" + name );
  }
  if ( type != "" )   
    Response.ContentType = type;
  Response.WriteFile( path );
  Response.End();    
}