2017-05-20 39 views
-1

私は、認証が正常に動作RESTサービスキャプチャ認証失敗は

@Service 
public class AuthenticationService { 

    private static final Logger log = LoggerFactory.getLogger(AuthenticationService.class); 

    @Autowired 
    private AuthenticationManager authenticationManager; 

    public void getAuthentication(AccountCredentials credentials) { 

     log.info("Authentication requested for user: " + credentials.getEmail()); 

     final Authentication authentication = authenticationManager.authenticate(
       new UsernamePasswordAuthenticationToken(
         credentials.getEmail(), 
         credentials.getPassword() 
       ) 
     ); 

     SecurityContextHolder.getContext().setAuthentication(authentication); 
    } 
} 

でユーザーを認証するために、クラスの下に持っているが、私は認証失敗があるたびにログに記録したいと思います。現在動作する方法は、デフォルトでSpring Securityによってステータスが返されるということです(403)。ログで認証失敗を取得するにはどうすればよいですか?私はさまざまな方法を試しましたが、403が返された後に他のコードは実行されていないので、コードに到達することはありません。私はまたtry catchブロックで試しましたが、それは流れを乱し、私は403というレスポンスをコーディングする必要があります。私は403ステータスメッセージを保持するのが好きで、ログにキャプチャされる以外に他のコードは実行されません。

+1

あなたはSpring Securityの代わりに取り組んでいますが、Spring Securityから放出されたイベントをいくつかの[failure events](http://docs.spring.io/spring-security)から聞くこともできます。 /site/docs/current/apidocs/org/springframework/security/authentication/event/AbstractAuthenticationFailureEvent.html)。 –

答えて

0

私は素晴らしい作品

M. Deinum

@Component 
public class AuthenticationFailureListener 
     implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> { 

    private static final Logger log = LoggerFactory.getLogger(AuthenticationFailureListener.class); 

    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) { 

     log.info("Authentication failed for user: " + event.getAuthentication().getPrincipal()); 

    } 
} 
からの返信後、このようにそれを実装しました。探していたものだけ。