Php 使用symfony2处理身份验证异常
我只想返回一条适当的消息,比如Php 使用symfony2处理身份验证异常,php,symfony,Php,Symfony,我只想返回一条适当的消息,比如returnnewresponse('authenticationfaild')通过API发送给我的客户机,但它的行为与下面代码中假定的不同 try{ $token = $this->get('security.authentication.manager') ->authenticate(new UsernamePasswordToken($username, $password, 'main
returnnewresponse('authenticationfaild')
通过API发送给我的客户机,但它的行为与下面代码中假定的不同
try{
$token = $this->get('security.authentication.manager')
->authenticate(new UsernamePasswordToken($username, $password, 'main'));
$this->get('security.context')->setToken($token);
}
catch (BadCredentialsException $e){
return new Response('authentication faild', 403);
}
返回的错误是html/css。。。登录表单的代码看看这个:
<?php
namespace YourBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class CatchErrorsEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return ["kernel.exception" => ['catchException', 200]];
}
/**
* @param GetResponseForExceptionEvent $evt
*/
public function catchException(GetResponseForExceptionEvent $evt)
{
$request = $evt->getRequest()->getRequestFormat('json');
if($request != 'json') {
return;
}
$response = $evt->getResponse() ?: new Response();
$evt->stopPropagation(); // stop the other listener to redirect to login
$evt->setResponse($response);
}
}
它返回完整的html/css。。。。假设取消显示登录表单的代码看一下要点:我已经使用异常侦听器实现了一个类似问题的解决方案。基本上,您可以设置一个侦听器来捕获所有异常,然后使用if$exception instanceof…
可以确定是哪个异常。然后我使用重定向到我的登录页面。我已经注册了侦听器以侦听OnCreeException(GetResponseForExceptionEvent$事件),如这里所述[link],我猜如果凭据不正确,但仍然存在相同的问题,将调用侦听器
<service class="YourBundle\EventListener\CatchErrorsEventSubscriber" id="your_bundle.catch_error_event_subscriber">
<tag name="kernel.event_subscriber"/>
</service>