Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从Spring Security抛出自定义响应_Java_Spring_Spring Security - Fatal编程技术网

Java 如何从Spring Security抛出自定义响应

Java 如何从Spring Security抛出自定义响应,java,spring,spring-security,Java,Spring,Spring Security,我们正在使用自定义身份验证提供程序对用户进行身份验证。该提供商将讨论我们的一项服务并验证用户(这是基本的身份验证) 有时我们的内部服务可能会因为未知的原因而中断。在这种情况下,我想向用户抛出一个自定义响应(500,“内部服务器错误”) 我们尝试抛出一个自定义异常(它扩展了身份验证异常)并在自定义身份验证入口点处理它。 但是我们看到定制异常没有向上传播。它被spring的其他一些异常(确切地说是拒绝访问的异常)掩盖了 如何让提供者向身份验证入口点抛出自定义异常,以便能够区分并抛出正确的响应 @Ov

我们正在使用自定义身份验证提供程序对用户进行身份验证。该提供商将讨论我们的一项服务并验证用户(这是基本的身份验证)

有时我们的内部服务可能会因为未知的原因而中断。在这种情况下,我想向用户抛出一个自定义响应(500,“内部服务器错误”)

我们尝试抛出一个自定义异常(它扩展了身份验证异常)并在自定义身份验证入口点处理它。 但是我们看到定制异常没有向上传播。它被spring的其他一些异常(确切地说是拒绝访问的异常)掩盖了

如何让提供者向身份验证入口点抛出自定义异常,以便能够区分并抛出正确的响应

@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");
       }
    }   
  }