Search code examples
symfonysecuritybasic-authentication

Symfony protect with HTTP Basic Authentication


I have an existing site built with Symfony 2.8 and I would like to add an extra layer of security by enabling HTTP Basic Auth only when a parameter is set to true in parameters.yml. Is it possible?

The site already has a form login enabled but I would like to hide the site completely with basic authentication if the parameter is true.

This is my security.yml:

main:
    pattern:             .*
    context:             user
    form_login:
        provider:       fos_userbundle
        login_path:     /user/login
        use_forward:    false
        check_path:     /user/login_check
        failure_path:   null
        default_target_path: /
    logout:
        path:           /user/logout
        target:         /user/login
    anonymous:          true

Solution

  • Since I didn't want to interfere with existing authentication I ended up using Apache:

    <VirtualHost *:80>
        ServerName mysite.com
        ServerAlias www.mysite.com
    
        DocumentRoot /var/www/html/mysite/current/web
        <Directory /var/www/html/mysite/current/web>
            AllowOverride None
            Order Allow,Deny
            Allow from All
    
            FallbackResource /app.php
    
            # THIS IS THE INTERESTING PART
            # --->
            AuthType Basic
            AuthName "Restricted Content"
            AuthUserFile /etc/apache2/.htpasswd
            Require valid-user
            # <---
        </Directory>
    
        # uncomment the following lines if you install assets as symlinks
        # or run into problems when compiling LESS/Sass/CoffeeScript assets
        # <Directory /var/www/project>
        #     Options FollowSymlinks
        # </Directory>
    
        # optionally disable the fallback resource for the asset directories
        # which will allow Apache to return a 404 error when files are
        # not found instead of passing the request to Symfony
        <Directory /var/www/html/mysite/current/web/bundles>
            FallbackResource disabled
        </Directory>
    
        ErrorLog ${APACHE_LOG_DIR}/mysite_error.log
        CustomLog ${APACHE_LOG_DIR}/mysite_access.log combined
    </VirtualHost>
    

    I created HTTP users and password with this command:

    sudo htpasswd -c /etc/apache2/.htpasswd stage
    

    The -c arguments needs to be here only the first time you are creating the file.

    For more info: https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-apache-on-ubuntu-14-04