Silex Security success_handler

2019-03-22 06:39发布

问题:

How i can set a success_handler (and failure_handler) for the form authentication provider?

Silex ignores me with this config:

<?php

use WebFactory\Security\UserProvider;

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'dev' => array(
            'pattern' => '^/(_(profiler|wdt)|css|images|js)/',
            'security' => false
        ),
        'default' => array(
            'pattern' => '^/.*$',
            'anonymous' => true,
            'form' => array(
                'login_path' => '/login',
                'check_path' => '/login_check',
                'success_handler' => 'authentication_handler', //<-- here
                'failure_handler' => 'authentication_handler', //<-- here
            ),
            'logout' => array('logout_path' => '/logout'),
            'users' => $app->share(function () use ($app) {
                        return new UserProvider($app['db']);
                    }),
        ),
    ),
    'security.access_rules' => array(
        array('^/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
        array('^/private$', 'ROLE_ADMIN'),
    ),
    'security.role_hierarchy' => array(
        'ROLE_SIMPLE_USER' => array('ROLE_USER'),
        'ROLE_ASSOCIATE' => array('ROLE_USER'),
    )
));

And this my custom (never invoked)

$app['authentication_handler'] = $app->share(function ($app) {
            return new \WebFactory\Security\AuthenticationHandler($app['url_generator']);
        });

It is a bug?

回答1:

The way you set success and failure handlers is by defining a service called security.authentication.success_handler.$name or security.authentication.failure_handler.$name, where $name is the name of the firewall.

For example:

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'foo' => ...,
    ),
));

$app['security.authentication.success_handler.foo'] = $app->share(function ($app) {
    return new Your\Own\SuccessHandler();
});

The security service provider will then detect the handlers by convention.