Silex基本身份验证 - 自定义故障处理程序

时间:2018-01-16 10:35:32

标签: php symfony authentication silex guard

我正在使用Silex构建api,我要求最终用户通过基本身份验证http标头标记发送凭据。我想创建一个自定义身份验证失败处理程序

我尝试了这个,但它没有用。错误功能永远不会被触发

$app['security.authentication.failure_handler.auth'] = function ($app) {
    return new AuthFailureHandler($app);
};

$app->register(new SecurityServiceProvider(), array(
    'security.firewalls'    => array(
        'foo'     => array('pattern' => '^/foo'), // Example of an url available as anonymous user
        'default' => array(
            'pattern' => '^.*$',
            'http'    => true,
            'users'   => function () use ($app) {
                return new UserProvider(new UserRepository($app['db']));
            },
        ),
    ),
    'security.access_rules' => array(
        // You can rename ROLE_USER as you wish
        array('^/.+$', UserRole::USER),
        array('^/foo$', ''), // This url is available as anonymous user
    ),
));

这是错误处理程序类

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

class AuthFailureHandler implements AuthenticationFailureHandlerInterface
{
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        return new JsonResponse(array(
            'type'    => 'error',
            'message' => 'Incorrect username or password.',
        ));
    }
}

0 个答案:

没有答案