Java 如何从Spring Security抛出自定义响应
我们正在使用自定义身份验证提供程序对用户进行身份验证。该提供商将讨论我们的一项服务并验证用户(这是基本的身份验证) 有时我们的内部服务可能会因为未知的原因而中断。在这种情况下,我想向用户抛出一个自定义响应(500,“内部服务器错误”) 我们尝试抛出一个自定义异常(它扩展了身份验证异常)并在自定义身份验证入口点处理它。 但是我们看到定制异常没有向上传播。它被spring的其他一些异常(确切地说是拒绝访问的异常)掩盖了 如何让提供者向身份验证入口点抛出自定义异常,以便能够区分并抛出正确的响应Java 如何从Spring Security抛出自定义响应,java,spring,spring-security,Java,Spring,Spring Security,我们正在使用自定义身份验证提供程序对用户进行身份验证。该提供商将讨论我们的一项服务并验证用户(这是基本的身份验证) 有时我们的内部服务可能会因为未知的原因而中断。在这种情况下,我想向用户抛出一个自定义响应(500,“内部服务器错误”) 我们尝试抛出一个自定义异常(它扩展了身份验证异常)并在自定义身份验证入口点处理它。 但是我们看到定制异常没有向上传播。它被spring的其他一些异常(确切地说是拒绝访问的异常)掩盖了 如何让提供者向身份验证入口点抛出自定义异常,以便能够区分并抛出正确的响应 @Ov
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = authentication.getName();
String password = authentication.getCredentials().toString();
try{
if (authenticationService.checkCredential(userName, password)) {
return new UsernamePasswordAuthenticationToken(
userName, password, new ArrayList<>());
} else {
return null;
}
}
catch (Exception e) {
e.printStackTrace();
throw new CustomAuthticationException("Internal Server Error");
}
}
您可以使用ControllerAdvice来抛出异常使用ControllerAdvice没有多大帮助,因为身份验证发生得更早,异常抛出得更早,并且异常解析程序不会捕获它。
@Component
public class MyBasicAuthenticationEntryPoint implements
AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e)
throws IOException, ServletException {
System.out.println(e.getMessage());
System.out.println("In MyBasicAuthenticationEntryPoint");
if(e.getCause() instanceof CustomAuthticationException){
System.out.println("Custom Exception");
}
}
}