Reputation: 103
how would one secure files on a web server? Id like them to be downloadable only by authenticated users How do i stop someone putting in the files URL and just downloading it without auth. lets say for instance - a user downloads the file - perhaps you have a controller that checks auth and streams them the file using this url: ie: site.com/controller/download/filename whats to stop people doing this with no auth directly: site.com/files/filename.ext
the direct link to the file essentially bypasses the whole web framework and just downloads the file.
perhaps im missing a fundamental here - but how to do this and keeps files private?
Thanks!
Upvotes: 1
Views: 703
Reputation: 196
Make a download action for your files based on unique encrypted id like below. Each file should be entered in file table which saves data like file name, original name, uploaded by, uuid etc and based on this data you can apply restrictions to the download action. You should also define access rule for the download action if you want only logged in user to be able to download the file.
public function actionDownload($id)
{
$file = File::findOne(['uuid'=>$id]);
if($file!=null)
{
$path = UPLOAD_BASE_PATH.'/'.$file->name;
if (file_exists($path) && !is_dir($path)) {
return Yii::$app->response->sendFile($path,$file->original_name);
}
}
throw new NotFoundHttpException("File not found");
}
Upvotes: 1
Reputation: 6169
If you don't want people allow to access files with direct link then you should save the files outside of the web root.
In yii2 your web root is in /web
folder and the folder should be set as web's document root. That will make server to point all request to it preventing any attempts to access files outside of /web
folder directly.
See apache docs for more info.
If you must have the folder in the place where it can be accessed directly you can use .htaccess to block any direct access to folder. How to do that is answered in this question: Deny access to one specific folder in .htaccess
Upvotes: 0