Search code examples
phpsymfonyauthorizationfosuserbundleweb-frontend

Access control for images in web frontend


My Symfony 3 web application has a user login control managed by FOSUserBundle. I am fine checking on login status on server side controlling all necessary actions a user may or may not do.

Now a user can upload images. There is a view that shows the user all of its images. To provide the frontend the needed img-pathes for this user-galery view I pass all the pathes for this users images to the frontend and then show it there.

This is were I get confused: How do I restrict access to this img-pathes to the respective (logged in) user only and deny it to all others? Or: How do I provide images to a frontend web view without using an img-path accessible for everyone? Is there a way to do this by using Symfony/FOSUserBundle functionality?


Solution

  • This works for me:

    Leave everything as it is but call a php-script to retrieve the images instead loading an image directly. So I only changed the "src" attribute in the img-tag to call a script and pass the img-name as a GET-parameter, in general this is:

    <img src="[server]/image.php?img=xy.jpg">
    

    The resulting route in Symfony is a bit different obviously, like:

    <img src="[server]/my/img/loading/route/xy.jpg">
    

    In the controller handling the request required access rights are checked for the requested image and a response is prepared:

    $response = new Response();
    $response->setContent( file_get_contents($imgPath) );
    $response->setStatusCode( Response::HTTP_OK );
    $response->headers->set( 'Content-type', $mimeType );
    $response->headers->set( 'Content-length', filesize($imgPath) );
    

    Returning this response from the respective controller action method now works fine.