php - 客户验证器 + form_login 选项破坏所有 csrf token

标签 php symfony csrf-protection

我有一个Symfony 3.3.13系统,有各种形式。

以这些形式实现“深度链接”,即。能够单击电子邮件链接、登录,然后重定向到表单,我添加了以下更改:

config.yml

framework:
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    ...
    more
    ...

安全.yml

security:
    providers:
        zog:
            id: app.zog_user_provider


    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~
            logout:
                path:   /logout
                target: /
            guard:
                authenticators:
                    - app.legacy_token_authenticator
                    - app.token_authenticator
                entry_point: app.legacy_token_authenticator
            form_login:                                         <--this line alone breaks CSRF 
                use_referer: true                               <--I tried partial combinations, none seems to make CSRF work
                login_path: /security/login
                use_forward: true
                success_handler: login_handler
                csrf_token_generator: security.csrf.token_manager   <--added based on answer, doesn't help

src/AppBundle/Resources/config/services.yml

login_handler:
    class: AppBundle\Service\LoginHandler
    arguments: ['@router', '@doctrine.orm.entity_manager', '@service_container']

src/AppBundle/Service/Loginhandler.php

<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 11/12/17
 * Time: 12:31 PM
 */

namespace AppBundle\Service;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Routing\RouterInterface;
use Doctrine\ORM\EntityManager;

class LoginHandler implements AuthenticationSuccessHandlerInterface
{
    private $router;
    private $container;
    private static $key;

    public function __construct(RouterInterface $router, EntityManager $em, $container) {

        self::$key = '_security.main.target_path';

        $this->router = $router;
        $this->em = $em;
        $this->session = $container->get('session');

    }

    public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {

        //check if the referer session key has been set
        if ($this->session->has( self::$key )) {

            //set the url based on the link they were trying to access before being authenticated
            $route = $this->session->get( self::$key );

            //remove the session key
            $this->session->remove( self::$key );
            //if the referer key was never set, redirect to a default route
            return new RedirectResponse($route);
        } else{

            $url = $this->generateUrl('portal_job_index');

            return new RedirectResponse($url);

        }



    }
}

我还确保在登录表单上启用了 csrf,如下所示:

src/AppBundle/resources/views/security/login.html.twig

        <form action="{{ path('app_security_login') }}" method="post" autocomplete="off">
            <input type="hidden" name="_csrf_token"
                   value="{{ csrf_token('authenticate') }}"
            >

应用程序/config/services.yml

app.legacy_token_authenticator:
    class: AppBundle\Security\LegacyTokenAuthenticator
    arguments: ["@router", "@session", "%kernel.environment%", "@security.csrf.token_manager"]

src/AppBundle/Security\legacyTokenAuthenticator

    class LegacyTokenAuthenticator extends AbstractGuardAuthenticator
    {
        private $session;

        private $router;

        private $csrfTokenManager;

        public function __construct(
            RouterInterface $router,
            SessionInterface $session,
            $environment,
            CsrfTokenManagerInterface $csrfTokenManager
        ) {
            if ($environment != 'test'){
                session_start();
            }
            $session->start();
            $this->setSession($session);
            $this->csrfTokenManager = $csrfTokenManager;
            $this->router = $router;
        }


        /**
         * @return mixed
         */
        public function getSession()
        {
            return $this->session;
        }


        /**
         * @param mixed $session
         */
        public function setSession($session)
        {
            $this->session = $session;
        }


        /**
         * Called on every request. Return whatever credentials you want,
         * or null to stop authentication.
         */
        public function getCredentials(Request $request)
        {
            $csrfToken = $request->request->get('_csrf_token');

            if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken('authenticate', $csrfToken))) {
                throw new InvalidCsrfTokenException('Invalid CSRF token.');
            }
            $session = $this->getSession();

            if (isset($_SESSION['ADMIN_logged_in']) && intval($_SESSION['ADMIN_logged_in'])){
                return $_SESSION['ADMIN_logged_in'];
            }
            return;
        }

        public function getUser($credentials, UserProviderInterface $userProvider)
        {
            return $userProvider->loadUserByUserId($credentials);
        }

        public function checkCredentials($credentials, UserInterface $user)
        {
            return $user->getUsername() == $credentials;
        }

        public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
        {
            return null;
        }

        public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
        {
            return null;
        }

        /**
         * Called when authentication is needed, but it's not sent
         */
        public function start(Request $request, AuthenticationException $authException = null)
        {
            $url = $this->router->generate('app_security_login');
            return new RedirectResponse($url);
        }

        public function supportsRememberMe()
        {
            return false;
        }


    }

当我在 security.yml 中添加以 form_login 开头的 5 行时,所有 CSRF 检查(包括登录表单上的检查)总是失败。我得到的错误是:

The CSRF token is invalid. Please try to resubmit the form. portalbundle_portal_job 

原因:

当我删除这 5 行时,所有 CSRF token 都可以工作。

最佳答案

这是我的一个启用了 csrf 保护的项目中的 security.yml 文件。我确实使用 FOS UserBundle,它看起来与您的不同,但您可能会在这里看到一些有帮助的东西。具体来说,必须指定 csrf 生成器才能使用 FOS UserBundle(在防火墙下:main:form_login)。我还设置了 access_control 模式,以便仅当用户通过特定角色进行身份验证时才能访问某些端点 - 但我认为这不会影响 csrf。见下文:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
        - { path: ^/event, role: ROLE_USER }

还在我的主 config.yml 中,我在框架下启用了 csrf。这是整个事情的一个片段:

framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~

关于php - 客户验证器 + form_login 选项破坏所有 csrf token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47762670/

相关文章:

php - 在 Twig 模板中使用全局变量的最简单方法是什么

symfony - 使用 nginx 在同一域上提供 react 前端和 php 后端

Symfony2 动态添加事件监听器

javascript - 用于刷新 CSRF token 的心跳/保活服务

php - joomla fatal error : Allowed memory size of 272629760 bytes exhausted

php - 搜索结果将显示在响应式弹出窗口中

javascript - 对于 Ajax 请求,我的函数应该通过 .fail() 回调返回什么?

html - SwiftmailerBundle 如何发送带有 html 内容的电子邮件?交响乐 2

java - Token/TokenSession 拦截器导致 HttpSession 上出现空指针

php - 如何通过 PHP 中的路径信息传递 URL 来防止 SSRF?