evilom
evilom

Reputation: 583

MVC Authentication on file download

How can I authenticate web users before allowing them to "src" an image or to download a file? There is also some condition that these files are publicly available.
I was thinking adding a filter in global.asax in RegisterGlobalFilters

Filter is something like..

public void OnFileRequest(string passToken)
{
   //validate passToken
   if (isValid(passToken))
      //allow download
   else
   {
     //authenticate using session
     if (authenticated)
        //allow download
     else
        //return exception
   }
}

Upvotes: 1

Views: 2513

Answers (3)

Rahul Uttarkar
Rahul Uttarkar

Reputation: 3645

The Files that are stored in some Folder, which can be downloaded on request(with authenticated user)

To Achieve this please follow the steps.

  • The Folder ( where files stored ) must have an web.config file or the normal web.config file must have definition to restrict the user authentication to Authenticated user only. using following xml Tags.

    <location path="~/Download_url_page(Folder,File url).aspx">
    
        <system.web>
    
            <authorization>
    
            <allow users="John"/> // allow John to Download file.
            <deny users="*"/>  // deny others
    
            </authorization>
    
        </system.web>
    
    </location>
    

Same way the logged in user(specific) / logged in users (not specific but authenticated users) . the download can be restricted.

<authorization>

<deny users="?"/> //this will restrict anonymous user access

</authorization>

I hope this solves your Problem.

Upvotes: 0

Tommy
Tommy

Reputation: 39807

Instead of directly linking to actual content, store a dictionary that maps a unique identifier (GUID?) to an actual file. Then, you can use an action result to allow the download or not.

Example:

public ActionResult GetImage(Guid id){
   if(SomeFunctionToDetermineIfAllowed()){
       return new FileResult(...);
   }else{
       return RedirectToAction("NotFound");
   }
}

Upvotes: 2

vivek
vivek

Reputation: 404

Use forms authentication and check for cookies.

Upvotes: 0

Related Questions