我正在使用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
吗?
答案 0 :(得分:1)
您可以收听the security events emitted by the security component,而不是使用通用error
功能,特别是 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);
});
请注意,这是未经测试的代码。
答案 1 :(得分:0)
尝试
$app->error(function (\Exception $e, $code) use ($app) {
// This code is never executed in case of Bad credentials
if($e instanceof AuthenticationException){
return new JsonResponse(["status_code"=>401, "error_message"=>"Bad credentials"], 401);
}
// ...
return new JsonResponse($contentResponse, $statusCode);
});
答案 2 :(得分:0)
由于我的代码结构,我决定检查after
中间件中的错误,抛出异常并用$app->error(...)
捕获它。
$app->after(function (Request $request, Response $response) {
// If Unauthorized
if ($response->getStatusCode() == 401)
throw new Exception('Unauthorized'); // This exception will be handled by "$app->error(...)"
});
$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) {
// ...
return new JsonResponse($contentResponse, $statusCode);
});