繁体   English   中英

如何处理spring ProviderManager中抛出的Spring安全性InternalAuthenticationServiceException

[英]How to handle spring security InternalAuthenticationServiceException thrown in Spring ProviderManager

ProviderManager在DaoAuthenticationProvider.class中检索用户时抛出InternalAuthenticationServiceException.class,

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

我想处理此异常并将我的自定义响应返回给客户端。

我不想通过编写自定义ProviderManager来处理这个问题。

对于所有其他OAuth异常,我可以使用Custom WebResponseExceptionTranslator处理异常。

但是我无法捕获像InternalAuthenticationServiceException.class这样的安全异常。

我没有选择将ErrorController与/ error路径一起使用,它打破了其他流程。

首先,你需要实现自己的AuthenticationEntryPoint名称不是真正自动解释...

例如,如果您需要始终返回状态代码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中,您需要将其设置为身份验证异常处理程序入口点。

...

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    ...

    @Autowired
    MyOwnAuthenticationEntryPoint myOwnAuthenticationEntryPoint;

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

就这样。 :)

您可以编写一个使用@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;
    }

}

我通过在我的过滤器中覆盖不成功的身份验证方法解决了这个问题,并使用所需的HTTP状态代码向客户端发送错误响应。 在我的例子中,我还创建了从我的服务抛出的自定义异常(RecordNotFoundException)。

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {

    if (failed.getCause() instanceof RecordNotFoundException) {
        response.sendError((HttpServletResponse.SC_NOT_FOUND), failed.getMessage());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM