2014-10-03 3 views
3

내가 나쁜 자격 증명으로 로그인 언제 내가 오류 메시지로 전체 스택 트레이스를 얻을 수 있기 때문에 내가 FOSUserBundle에 문제가있어에서의 AuthenticationHandler에서 설정 flashMessage :Symfony2

오류! 예외 /var/www/html/vendor/symfony/symfony/src/Symfony/구성 요소/보안/코어/인증/공급자에 'BadfredentialsException'메시지가 포함 된 'symfony \ Component \ Security \ Core \ Exception \ BadCredentialsException'메시지가있는 예외 ' /UserAuthenticationProvider.php:90

그리고 저에게는보기 흉하지만 사용자에게는 매우 못 생깁니다. 그래서 나는 두 가지 해결책을 생각하고있다 : 나는 작업하고있는 AJAX 로그인으로 변경한다. 그러나 작동하지 않는다. 또는 나는 잘못된 것을하고있다. (아래에 설명 할 것이다.) 그 추악한 메시지를 바꾸는 방법을 찾았다. 이것은 아직 하나의 조언이 도움이 될 것입니다).

<?php 

namespace UsuarioBundle\Handler; 

use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Bundle\FrameworkBundle\Routing\Router; 
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; 
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; 
use Symfony\Component\Security\Core\Exception\AuthenticationException; 

class AuthenticationHandler 
    implements AuthenticationSuccessHandlerInterface, 
    AuthenticationFailureHandlerInterface 
{ 
    private $router; 

    public function __construct(Router $router) 
    { 
     $this->router = $router; 
    } 

    public function onAuthenticationSuccess(Request $request, TokenInterface $token) 
    { 
     if ($request->isXmlHttpRequest()) { 
      // do I need something here? 
     } else { 
      // If the user tried to access a protected resource and was forces to login 
      // redirect him back to that resource 
      if ($targetPath = $request->getSession()->get('_security.target_path')) { 
       $url = $targetPath; 
      } else { 
       // Otherwise, redirect him to wherever you want 
       $url = $this->router->generate('user_view', array('nickname' => $token->getUser()->getNickname())); 
      } 

      return new RedirectResponse($url); 
     } 
    } 

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) 
    { 
     if ($request->isXmlHttpRequest()) { 
      // Handle XHR here 
     } else { 
      // Create a flash message with the authentication error message 
      $request->getSession()->setFlash('error', $exception->getMessage()); 
      $url = $this->router->generate('user_login'); 

      return new RedirectResponse($url); 
     } 
    } 
} 
  • 서비스를 정의하고 핸들러 등록 :

    parameters: 
        vendor_security.authentication_handler: UsuarioBundle\Handler\AuthenticationHandler 
    
    services: 
        authentication_handler: 
         class: %vendor_security.authentication_handler% 
         arguments: [@router] 
         tags: 
          - { name: 'monolog.logger', channel: 'security' } 
    
    • AuthenticationHandler 구현 : 지금이 최초의 솔루션에 대한

      내가 한 일이다

      의 참조를 변경하십시오. 0 :

      방화벽 : 주 : 패턴 ^/ form_login : 공급자 : fos_userbundle csrf_provider/로그인 check_path :/login_check success_handler : authentication_handler failure_handler : authentication_handler

      login_path form.csrf_provider
       logout: 
            path: fos_user_security_logout 
            target:/
            invalidate_session: false 
           anonymous: ~ 
      

    하지만이 오류는 잘못된 자격 증명으로 ogin :

    클래스 에 방법 "setFlash"를 호출하는 시도 "심포니 \ 구성 요소 \ HttpFoundation 세션 \ \ 세션" /var/www/html/src/UsuarioBundle/Handler/AuthenticationHandler.php에 라인 52.

    왜? 나는 getSession() 방법을 검사하고 use 진술에 포함되어있는 HttpFoundation의 일부입니다. 그래서 내가 여기서 잘못하고있는 것은 무엇입니까?

    참고 : 코드를 주로 this 주제에서 취합니다. 그래서 나는 그것에 대해 여전히 의문을 가지고 있습니다.

  • +1

    당신은 setFlash 대신에 session-> getFlashBag() -> add()를 사용해야한다고 생각합니다. – Alex

    답변

    9

    $request->getSession()->setFlash('error', 'error');은 "이전"심포니 버전 표기법입니다.

    지금 당신은 또한

    $reqest->getSession()->getFlashBag()->add('error', $exception->getMessage()); 
    

    를 사용해야합니다, 당신은 확실히 $exception 문자 메시지를 보여줄 수있는 좋은 방법입니다입니까? 내 말은,이 플래시가 어떤 페이지에 표시되는지는 모르겠지만, 사용자 나 관리자가 PHP와 프로그래밍에 대해 거의 알지 못한다면 그 페이지를 볼 수 있으므로 메시지를 보내려면 용도에 맞게 메시지를 기록해야하지만 사용자에게 다른 메시지를 보여야합니다.

    +0

    컨테이너가 핸들러에 삽입되지 않았으므로'$ this-> get ('session')'을 사용하지 않아야합니다. – qooplmao

    +0

    @Qoop : 네 말이 맞아 : 나는 "자동 조종 장치"응답 모드에 있었고 코드 스 니펫이 컨트롤러 하나가 아니라는 것을 알아 차리지 못했다. – DonCallisto

    +0

    @Qoop : edited ... – DonCallisto