예제 #1
0
 /**
  * Handles security related exceptions.
  *
  * @param Event $event An Event instance
  */
 public function handleException(Event $event)
 {
     $exception = $event->getParameter('exception');
     $request = $event->getParameter('request');
     if ($exception instanceof AuthenticationException) {
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage()));
         }
         try {
             $response = $this->startAuthentication($request, $exception);
         } catch (\Exception $e) {
             $event->setParameter('exception', $e);
             return;
         }
     } elseif ($exception instanceof AccessDeniedException) {
         $token = $this->context->getToken();
         if (null === $token || $token instanceof AnonymousToken) {
             if (null !== $this->logger) {
                 $this->logger->info('Access denied (user is anonymous); redirecting to authentication entry point');
             }
             try {
                 $response = $this->startAuthentication($request, new InsufficientAuthenticationException('Full authentication is required to access this resource.', $token, 0, $exception));
             } catch (\Exception $e) {
                 $event->setParameter('exception', $e);
                 return;
             }
         } else {
             if (null !== $this->logger) {
                 $this->logger->info('Access is denied (and user is not anonymous)');
             }
             if (null === $this->errorPage) {
                 return;
             }
             $subRequest = Request::create($this->errorPage);
             $subRequest->attributes->set(SecurityContext::ACCESS_DENIED_ERROR, $exception->getMessage());
             try {
                 $response = $event->getSubject()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
             } catch (\Exception $e) {
                 if (null !== $this->logger) {
                     $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage()));
                 }
                 $event->setParameter('exception', new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
                 return;
             }
             $response->setStatusCode(403);
         }
     } else {
         return;
     }
     $event->setReturnValue($response);
     return true;
 }