2016-09-30 76 views
1

的ProviderManager拋出InternalAuthenticationServiceException.class在檢索用戶DaoAuthenticationProvider.class,如何處理在春天的ProviderManager

loadedUser = this.getUserDetailsService().loadUserByUsername(username); 

拋出春季安全InternalAuthenticationServiceException我要處理這個異常,並返回我給客戶定製的響應。

我不想通過編寫自定義ProviderManager來處理此問題。

對於所有其他OAuth異常,我可以使用Custom WebResponseExceptionTranslator處理異常。

但我無法捕獲像InternalAuthenticationServiceException.class安全異常。

我沒有選擇使用ErrorController和/ error路徑,它打破了其他流程。

+0

什麼是你用於Web的框架?彈簧控制器或澤西島? – shazin

+0

@shazin我正在使用Spring引導和彈簧安全2.0.8 – Harish

回答

0

你可以寫一個課程,註釋編號爲@ControllerAdvice,並有一個@ExceptionHandler(value=InternalAuthenticationServiceException.class)

例如: -

@ControllerAdvice 
public class ExceptionHandler { 

    @ExceptionHandler(InternalAuthenticationServiceException.class) 
    public ResponseEntity<String> handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) { 
     ResponseEntity<String> response = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); 
     return response; 
    } 

} 
+0

ControllerAdvice沒有得到調用時拋出的安全性的異常。我正在使用@EnableAuthorizationServer,因此我的服務中沒有任何顯式控制器。 – Harish

2

首先,你需要實現自己的的AuthenticationEntryPoint名字是不是真的autoexplicative ...

例如,如果你需要經常返回狀態代碼200(只爲學習目的,請不要在現實世界中做...)

@Component("myOwnAuthenticationEntryPoint") 
public class MyOwnAuthenticationEntryPoint implements AuthenticationEntryPoint { 
    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException { 
     response.sendError(HttpServletResponse.SC_OK, "Unauthorized"); 
    } 

然後在你的WebSecurityConfig中,你需要t o將其設置爲您的身份驗證異常處理程序入口點。

... 

public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    ... 

    @Autowired 
    MyOwnAuthenticationEntryPoint myOwnAuthenticationEntryPoint; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.exceptionHandling().authenticationEntryPoint(myOwnAuthenticationEntryPoint); 
    ... 
    } 

就是這樣。 :)