简体   繁体   English

Symfony安全文件夹与资产

[英]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. 我正在尝试使用某些资产(pdf文件等)来保护我的Symfony 2.7项目的公共文件夹,因此只有登录用户才能访问它们。

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. 我希望每个人(甚至是匿名用户)都能访问web/uploads/public文件夹中的所有文件,但只能访问注册用户访问web/uploads/secured文件夹中的文件。

I already tried to set up security.yml with this rule in access_control : 我已经尝试在access_control使用此规则设置security.yml

    - { 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? 或者我需要制作某种控制器,它将覆盖我的文件路由,另外还要检查是否允许用户查看文件?

Symfony (or any other PHP script) is not called when viewing static files. 查看静态文件时不会调用Symfony(或任何其他PHP脚本)。 It's only called when your front controller is hit (app.php). 它仅在你的前控制器命中时被调用(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. 使用您的Web服务器来保护对资产的访问,或者将它们放在公共目录之外并使用控制器来为它们提供服务。

From Symnfony 3.2 you can store your files in a non public route. 从Symnfony 3.2,您可以将文件存储在非公共路径中。 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM