[英]handle authentication exception with symfony2
我想簡單地返回一條適當的消息,比如return new Response('authentication faild');
通過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);
}
}
此偵聽器將捕獲異常,您可以按所需方式發送響應。 僅在此示例中,請求是json請求。
不要忘記將訂戶注冊為服務:
<service class="YourBundle\EventListener\CatchErrorsEventSubscriber" id="your_bundle.catch_error_event_subscriber">
<tag name="kernel.event_subscriber"/>
</service>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.