Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony secure folder with assets

I am trying to secure public folder of my Symfony 2.7 project with some assets (pdf files etc) so only logged in user can reach them.

Imagine folder structure:

-- web
    | -- uploads
            | -- public
            | -- secured

I want to everyone (even anonymous users) reach all files in web/uploads/public folder but to have access only for registered user to files in web/uploads/secured folder.

I already tried to set up security.yml with this rule in access_control:

    - { path: ^/uploads/secured, role: ROLE_USER }

But this works only for routes not for files in my public folder.

Is this even possible? Or I need to make some kind of controller which will be overwriting routes for my files and additionally checking if user is granted to see files?

like image 859
Cockootec Avatar asked Feb 22 '26 16:02

Cockootec


2 Answers

Symfony (or any other PHP script) is not called when viewing static files. It's only called when your front controller is hit (app.php).

Either use your web server to secure access to the assets, or put them outside of a public directory and use a controller to serve them.

like image 133
Jakub Zalas Avatar answered Feb 25 '26 06:02

Jakub Zalas


From Symnfony 3.2 you can store your files in a non public route. Route the files from a controller checking permissions or whatever you need. Then you can use the file controller helper to serve them.

Class FileController extends Controller 
{

  /**
  * @Route("/file/download/{id}", requirements={"id": "\d+"}, name="file_download")
  */
  public function downloadAction($id)
  {
    $file = $this->repository->find($id);
    $path = __DIR__ . '/../../var/files/' . $file->getFilePath . '/' . $file->getFileName();
    return $this->file($path);
  }
}
like image 35
juananruiz Avatar answered Feb 25 '26 08:02

juananruiz