Prevent direct access to uploaded files only for unauthorized users - Symfony












4















I am trying to give direct access to uploaded files only for logged in users in my website for security concerns. I tried this configuration but it seems to be working on download image.



This is my Twig file code where I am showing the image.



{% 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 %}


configuration for sonata media below.



Sonata_media.yml



sonata_media:
# if you don't use default namespace configuration
#class:
# media: MyVendorMediaBundleEntityMedia
# gallery: MyVendorMediaBundleEntityGallery
# gallery_has_media: MyVendorMediaBundleEntityGalleryHasMedia
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









share|improve this question

























  • can you put some snapshot of code? Or explain how you're making image response

    – akbansa
    Jan 1 at 9:47











  • @akbansa added code related to the media. let me know if you need more explanation.

    – Owais Aslam
    Jan 1 at 10:33
















4















I am trying to give direct access to uploaded files only for logged in users in my website for security concerns. I tried this configuration but it seems to be working on download image.



This is my Twig file code where I am showing the image.



{% 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 %}


configuration for sonata media below.



Sonata_media.yml



sonata_media:
# if you don't use default namespace configuration
#class:
# media: MyVendorMediaBundleEntityMedia
# gallery: MyVendorMediaBundleEntityGallery
# gallery_has_media: MyVendorMediaBundleEntityGalleryHasMedia
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









share|improve this question

























  • can you put some snapshot of code? Or explain how you're making image response

    – akbansa
    Jan 1 at 9:47











  • @akbansa added code related to the media. let me know if you need more explanation.

    – Owais Aslam
    Jan 1 at 10:33














4












4








4


1






I am trying to give direct access to uploaded files only for logged in users in my website for security concerns. I tried this configuration but it seems to be working on download image.



This is my Twig file code where I am showing the image.



{% 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 %}


configuration for sonata media below.



Sonata_media.yml



sonata_media:
# if you don't use default namespace configuration
#class:
# media: MyVendorMediaBundleEntityMedia
# gallery: MyVendorMediaBundleEntityGallery
# gallery_has_media: MyVendorMediaBundleEntityGalleryHasMedia
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









share|improve this question
















I am trying to give direct access to uploaded files only for logged in users in my website for security concerns. I tried this configuration but it seems to be working on download image.



This is my Twig file code where I am showing the image.



{% 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 %}


configuration for sonata media below.



Sonata_media.yml



sonata_media:
# if you don't use default namespace configuration
#class:
# media: MyVendorMediaBundleEntityMedia
# gallery: MyVendorMediaBundleEntityGallery
# gallery_has_media: MyVendorMediaBundleEntityGalleryHasMedia
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






php symfony sonata-media-bundle






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 5 at 11:57









halfer

14.6k758114




14.6k758114










asked Jan 1 at 6:06









Owais AslamOwais Aslam

1,1541926




1,1541926













  • can you put some snapshot of code? Or explain how you're making image response

    – akbansa
    Jan 1 at 9:47











  • @akbansa added code related to the media. let me know if you need more explanation.

    – Owais Aslam
    Jan 1 at 10:33



















  • can you put some snapshot of code? Or explain how you're making image response

    – akbansa
    Jan 1 at 9:47











  • @akbansa added code related to the media. let me know if you need more explanation.

    – Owais Aslam
    Jan 1 at 10:33

















can you put some snapshot of code? Or explain how you're making image response

– akbansa
Jan 1 at 9:47





can you put some snapshot of code? Or explain how you're making image response

– akbansa
Jan 1 at 9:47













@akbansa added code related to the media. let me know if you need more explanation.

– Owais Aslam
Jan 1 at 10:33





@akbansa added code related to the media. let me know if you need more explanation.

– Owais Aslam
Jan 1 at 10:33












2 Answers
2






active

oldest

votes


















3














I followed these steps to achieve this requirement.




  1. Created a function and added its route in firewall, so anonymous users cannot go to that path.

  2. Created a route to set its path.

  3. Got media id in the function and did the functionality to return the file.

  4. Called the function by its path with parameter mediaId instead of calling direct media in twig.


Here is the code.



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 }


Controller



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


Twig



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





share|improve this answer

































    -2














    Yes, you are right. The link you provide contain the download strategy but does not contain the upload strategy. I also has explore the documentation and advance configuration as well.



    Unfortunately, there is no such thing mention in the documentation. Well, in this case you have to write your own uploadStrategyInterface like the DownloadStrategyInterface one. Then write your own security upload strategy or you can use the "sonata.media.security.connected_strategy" one. Here is the link that helps you.






    share|improve this answer


























    • The question and answer both are irrelavent

      – akbansa
      Jan 1 at 9:48











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993362%2fprevent-direct-access-to-uploaded-files-only-for-unauthorized-users-symfony%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    I followed these steps to achieve this requirement.




    1. Created a function and added its route in firewall, so anonymous users cannot go to that path.

    2. Created a route to set its path.

    3. Got media id in the function and did the functionality to return the file.

    4. Called the function by its path with parameter mediaId instead of calling direct media in twig.


    Here is the code.



    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 }


    Controller



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


    Twig



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





    share|improve this answer






























      3














      I followed these steps to achieve this requirement.




      1. Created a function and added its route in firewall, so anonymous users cannot go to that path.

      2. Created a route to set its path.

      3. Got media id in the function and did the functionality to return the file.

      4. Called the function by its path with parameter mediaId instead of calling direct media in twig.


      Here is the code.



      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 }


      Controller



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


      Twig



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





      share|improve this answer




























        3












        3








        3







        I followed these steps to achieve this requirement.




        1. Created a function and added its route in firewall, so anonymous users cannot go to that path.

        2. Created a route to set its path.

        3. Got media id in the function and did the functionality to return the file.

        4. Called the function by its path with parameter mediaId instead of calling direct media in twig.


        Here is the code.



        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 }


        Controller



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


        Twig



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





        share|improve this answer















        I followed these steps to achieve this requirement.




        1. Created a function and added its route in firewall, so anonymous users cannot go to that path.

        2. Created a route to set its path.

        3. Got media id in the function and did the functionality to return the file.

        4. Called the function by its path with parameter mediaId instead of calling direct media in twig.


        Here is the code.



        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 }


        Controller



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


        Twig



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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 9 at 8:48









        halfer

        14.6k758114




        14.6k758114










        answered Jan 9 at 6:31









        Owais AslamOwais Aslam

        1,1541926




        1,1541926

























            -2














            Yes, you are right. The link you provide contain the download strategy but does not contain the upload strategy. I also has explore the documentation and advance configuration as well.



            Unfortunately, there is no such thing mention in the documentation. Well, in this case you have to write your own uploadStrategyInterface like the DownloadStrategyInterface one. Then write your own security upload strategy or you can use the "sonata.media.security.connected_strategy" one. Here is the link that helps you.






            share|improve this answer


























            • The question and answer both are irrelavent

              – akbansa
              Jan 1 at 9:48
















            -2














            Yes, you are right. The link you provide contain the download strategy but does not contain the upload strategy. I also has explore the documentation and advance configuration as well.



            Unfortunately, there is no such thing mention in the documentation. Well, in this case you have to write your own uploadStrategyInterface like the DownloadStrategyInterface one. Then write your own security upload strategy or you can use the "sonata.media.security.connected_strategy" one. Here is the link that helps you.






            share|improve this answer


























            • The question and answer both are irrelavent

              – akbansa
              Jan 1 at 9:48














            -2












            -2








            -2







            Yes, you are right. The link you provide contain the download strategy but does not contain the upload strategy. I also has explore the documentation and advance configuration as well.



            Unfortunately, there is no such thing mention in the documentation. Well, in this case you have to write your own uploadStrategyInterface like the DownloadStrategyInterface one. Then write your own security upload strategy or you can use the "sonata.media.security.connected_strategy" one. Here is the link that helps you.






            share|improve this answer















            Yes, you are right. The link you provide contain the download strategy but does not contain the upload strategy. I also has explore the documentation and advance configuration as well.



            Unfortunately, there is no such thing mention in the documentation. Well, in this case you have to write your own uploadStrategyInterface like the DownloadStrategyInterface one. Then write your own security upload strategy or you can use the "sonata.media.security.connected_strategy" one. Here is the link that helps you.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 1 at 14:59

























            answered Jan 1 at 9:30









            Saif ur RehmanSaif ur Rehman

            4581415




            4581415













            • The question and answer both are irrelavent

              – akbansa
              Jan 1 at 9:48



















            • The question and answer both are irrelavent

              – akbansa
              Jan 1 at 9:48

















            The question and answer both are irrelavent

            – akbansa
            Jan 1 at 9:48





            The question and answer both are irrelavent

            – akbansa
            Jan 1 at 9:48


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993362%2fprevent-direct-access-to-uploaded-files-only-for-unauthorized-users-symfony%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            Npm cannot find a required file even through it is in the searched directory