【问题标题】:spring security: send redirect in case of exceptionspring security:在出现异常时发送重定向
【发布时间】:2016-01-06 02:39:55
【问题描述】:

我有一个关于 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 通常允许这样做,在这种情况下我如何实现我的计划?

提前谢谢你。

【问题讨论】:

  • “仅在控制器级别上工作,而不是更早。”你这是什么意思?
  • @Ankit,SM_USER头的预认证发生在控制器类的方法开始之前,所以上面描述的类ExceptionResolver不会捕捉到loadUserByUsername()类的loadUserByUsername()方法抛出的异常

标签: java spring-mvc authentication spring-security


【解决方案1】:

如果您使用的是 Spring xml,您可以在像这样失败时使用 @PostConstruct 调用一个 bean

<sec:form-login authentication-failure-handler-ref="afterLoginFail"

登录失败后示例

public class AfterLoginFail extends SimpleUrlAuthenticationFailureHandler {

    @PostConstruct
    public void init() {
        setDefaultFailureUrl("/login?status=failure");
    }

}

或者,如果您使用 javaconfig,请使用 formLogin().failureUrl(authenticationFailureUrl).failureHandler()

【讨论】:

  • 谢谢!我需要用@Bean 注释注册AfterLoginFail 吗?如何添加此 ti spring 安全性?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2017-02-07
  • 2017-12-06
  • 2011-08-04
相关资源
最近更新 更多