我正在使用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/