php – 防止仅为未经授权的用户直接访问上传的文件 – Symfony

我试图直接访问我的网站中登录用户的上传文件,以解决安全问题.我尝试了
this配置,但它似乎正在下载图像.

这是我正在显示图像的Twig文件代码.

{% if(req.media!='') %}
      <a href="{% path req.media, 'reference' %}"
      data-fancybox class="fancybox">
       <img src="{% path (req.media), 'reference' %}" alt="" width="70px"
        height="70px"/>
      </a>
{% endif %}

下面是奏鸣曲媒体的配置.

Sonata_media.yml

sonata_media:
# if you don't use default namespace configuration
#class:
#    media: MyVendor\MediaBundle\Entity\Media
#    gallery: MyVendor\MediaBundle\Entity\Gallery
#    gallery_has_media: MyVendor\MediaBundle\Entity\GalleryHasMedia
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr it is mandatory to choose one here
default_context: default # you need to set a context
contexts:
    default:  # the default context is mandatory
        download:
            strategy: sonata.media.security.forbidden_strategy
        providers:
            #- sonata.media.provider.dailymotion
            #- sonata.media.provider.youtube
            - sonata.media.provider.image
            - sonata.media.provider.file
            #- sonata.media.provider.vimeo

最佳答案 我按照这些步骤来实现这一要求.

>创建了一个函数并在防火墙中添加了它的路由,因此匿名用户无法访问该路径.
>创建了一条路径来设置其路径.
>在函数中获得了媒体ID并执行了返回文件的功能.
>使用参数mediaId通过其路径调用函数,而不是在树枝中调用直接媒体.

这是代码.

security.yml

- { path: ^/user(.*), roles: ROLE_DASHBOARD_USER }

使用routing.yml

cms_direct_access_uploaded_files:
path:     /user/image-return/{fileId}
defaults: { _controller: CMSFrontUserBundle:Dashboard:DirectAccessUploadedMedia }

调节器

    public function DirectAccessUploadedMediaAction(Request $request,$fileId = null){
    $user = $this->getUser();
    if(!empty($user)){
        $DM = $this->getDoctrineManager();
        $media = $DM->getRepository('ApplicationSonataMediaBundle:Media')->find($fileId);
        if(!empty($media)) {
            $provider   = $this->container->get( $media->getProviderName() );
            $format     = $provider->getFormatName( $media, 'reference' );
            $url        = $provider->generatePublicUrl( $media, $format );
            $ext = pathinfo($url, PATHINFO_EXTENSION);
            $returnFile = $_SERVER['DOCUMENT_ROOT'] .'/web'. $url;
            if (file_exists($returnFile)) {
                if($ext == 'pdf'){
                    header("Content-Type: application/pdf");
                }else{
                    header("Content-Type: image/jpeg");
                }
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($returnFile));
                readfile($returnFile);
                exit;
            }
        }else{
            throw $this->createAccessDeniedException('Forbidden!');
        }
    }else{
        throw $this->createAccessDeniedException('Forbidden!');
    }
}

枝条

{{ url('homepage') }}user/image-return/{{ req.media.id }}
点赞