[英]spring security: send redirect in case of exception
我有一個關於Spring Security的問題。
我的想法是,在SM_USER標頭錯誤的情況下,我不想發送未捕獲的異常(就像我的類CustomUserDetailsService
loadUserByUsername
方法一樣)。
public class CustomUserDetailsService implements UserDetailsService {...}
我想捕獲它,然后重定向到默認頁面(帶有映射my/default/page
),並在其中寫入消息文本,例如: 請重試 。
我已經有一個ExceptionResolver,但它僅在控制器級別有效,不適用於較早版本。
@ControllerAdvice
public class ExceptionResolver {
@ExceptionHandler(PreAuthenticatedCredentialsNotFoundException.class)
public ResponseEntity<?> handleBindException(PreAuthenticatedCredentialsNotFoundException e) {
log.error(e.getMessage(), e);
...
return response;
}
@ExceptionHandler(UsernameNotFoundException.class)
public ResponseEntity<?> handleBindException(UsernameNotFoundException e) {
log.error(e.getMessage(), e);
...
return response;
}
}
據我了解,我需要為這種情況實現一個新的異常解析器,但是當我嘗試在應用程序上下文中構建它時,我的整個程序都會崩潰。
@RequestMapping("/resource")
public class GlobalExceptionResolver extends AbstractHandlerExceptionResolver{
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse responce, Object handler, Exception exception) {
try {
responce.sendRedirect("/my/defualt/page");
} catch (IOException e) {
log.error(e);
}
ModelAndView mav = new ModelAndView();
if(exception instanceof PreAuthenticatedCredentialsNotFoundException){
mav.addObject("errorMessage","This user does not exist");
}
else if(exception instanceof UsernameNotFoundException){
mav.addObject("errorMessage","This user is too old");
}
return mav;
}
}
因此,請您解釋一下,如果Spring Security允許的話,在這種情況下如何實現我的計划?
先感謝您。
如果您使用的是Spring xml,則像這樣失敗時可以使用@PostConstruct調用一個bean
<sec:form-login authentication-failure-handler-ref="afterLoginFail"
AfterLoginFail示例
public class AfterLoginFail extends SimpleUrlAuthenticationFailureHandler {
@PostConstruct
public void init() {
setDefaultFailureUrl("/login?status=failure");
}
}
或者,如果您使用javaconfig,請使用formLogin().failureUrl(authenticationFailureUrl)
或.failureHandler()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.