php - 如何在Silex中捕获身份验证错误?

标签 php error-handling silex

我正在使用Silex框架开发Rest API,并使用SecurityServiceProvider。但是,如果用户发送错误的凭据抛出HTTP,我不知道如何捕获错误以显示如下内容:

{"status_code":401, "error_message":"Bad credentials"}

以下是我的代码的一部分:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'default' => array(
            'pattern' => '^.*$',
            'stateless' => true,
            'http' => true,
            'users' => $app->share(function() use ($app) {
                return new App\Providers\UserProvider($app['db']);
            }),
        ),
    ),
));

// ...

$app->error(function (\Exception $e, $code) use ($app) {
    // This code is never executed in case of Bad credentials

    // ...

    return new JsonResponse($contentResponse, $statusCode);
});

先感谢您

编辑

我已经看到可以使用$app['security.authentication.failure_handler.'.$name]了,但是在我的情况下从来没有处理过。
$app['security.authentication.failure_handler.default'] = $app->share(function ($app) {
     // This code is never executed
     return new MySuccessHandler();
});

是因为'http' => true吗?

最佳答案

除了使用通用的error函数,您还可以侦听the security events emitted by the security component,尤其是security.authentication.failure之一。

为此,您只需要调用 on 方法:

<?php

use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent

//...
$app->on('security.authentication.failure', function(AuthenticationFailureEvent $event) {
  // you can do some checks if you want, but there's no need...

  return new JsonResponse($contentResponse, $statusCode);
});

请记住,这是未经测试的代码。

关于php - 如何在Silex中捕获身份验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38564201/

相关文章:

php - array_merge 与 union 在 PHP 中的性能

ajax - HttpPost上的ASP MVC3 HandleError

python - 这个简单的 python 代码有什么问题?

forms - Spring 形式 :errors customization

symfony - Silex + Twig : form_widget() not found, 即使安装了 Symfony Bridge

symfony - Silex:设置防火墙 session 生命周期

php - 以干净的方式正确覆盖 WooCommerce 函数 WC_Price()

php - 如何在 Laravel 5.4 本地作用域中的关系调用中使用?

javascript - JSON 输入意外结束

php - 硅胶 : allow user to change langage by clicking on html element and keeping clean URL