首页 > 解决方案 > Symfony 使用 HTTP 基本身份验证保护

问题描述

我有一个使用 Symfony 2.8 构建的现有站点,我想通过仅在 parameters.yml 中的参数设置为 true 时启用 HTTP Basic Auth 来添加额外的安全层。可能吗?

该站点已经启用了表单登录,但如果参数为true.

这是我的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

标签: symfonysecuritybasic-authentication

解决方案


由于我不想干扰现有的身份验证,我最终使用了 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>

我使用以下命令创建了 HTTP 用户和密码:

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

只有第-c一次创建文件时,参数才需要在这里。

欲了解更多信息:https ://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-apache-on-ubuntu-14-04


推荐阅读