Cockootec
Cockootec

Reputation: 546

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?

Upvotes: 3

Views: 2793

Answers (2)

juananruiz
juananruiz

Reputation: 777

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);
  }
}

Upvotes: 1

Jakub Zalas
Jakub Zalas

Reputation: 36241

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.

Upvotes: 4

Related Questions