customer authenticator + form_login options打破所有csrf标记

问题描述 投票:13回答:2

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

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

config.yml

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

security.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 /资源/配置/ services.yml

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

的src /的appbundle /服务/ 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 /资源/视图/安全/ login.html.twig

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

app / config / services.yml

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

SRC /的appbundle /安全\ 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;
        }


    }

所有CSRF检查 - 包括在登录表单上 - 总是在我从security_yml以form_login开头添加5行时失败。我得到的错误是:

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

引起:

当我删除这5行时,所有CSRF令牌都有效。

php symfony csrf-protection
2个回答
6
投票

这是我的一个项目中的security.yml文件,它启用了csrf保护。我确实使用了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: ~

1
投票

对我来说,手动处理Symfony CSRF令牌是一个主要的头脑。如果没有这样做只是为了学习如何去做,我认为几乎总有一个更简单的解决方案。

我在登录时的CSRF保护解决方案不会遇到此问题。

我使用Form组件创建表单登录。

function loginAction()
{
    $login = $this->createForm(LoginType::class);
    $authenticationUtils = $this->get('security.authentication_utils');
    $error = $authenticationUtils->getLastAuthenticationError();

    return $this->render('Path/to/login.html.twig', [
        'form' => $login->createView(),
        'error' => $error,
    ]);
}

LoginType.php:

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
//...

class LoginType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }
}

login.html.twig:

{# template information #}
{{ form_start(form) }}
    {{ form_row(form.username, {
        'full_name': '_username'
    } ) }}
    {{ form_row(form.password, {
        'full_name': '_password'
    } ) }}
{{ form_end(form) }}
{# template information #}

security.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: /
            form_login:
                use_referer: true                  
                login_path: /security/login
                success_handler: login_handler
                always_use_default_target_path: false
                default_target_path: /

如果您在表单上启用了CSRF,那么您的登录表单将受CSRF保护,无需任何自定义Guard身份验证器。

© www.soinside.com 2019 - 2024. All rights reserved.