gpt4 book ai didi

java - 捕获 AuthenticationProvider 中抛出的异常

转载 作者:行者123 更新时间:2023-12-01 22:09:36 25 4
gpt4 key购买 nike

我正在实现自定义“AuthenticationProvider”。如果未经过身份验证,我将在“身份验证”函数内抛出异常,如下所示。

public class DelegatingLdapAuthenticationProvider implements AuthenticationProvider {

private ActiveDirectoryLdapAuthenticationProvider primaryProvider;
private List<ActiveDirectoryLdapAuthenticationProvider> secondaryProviders = new ArrayList<>();

public DelegatingLdapAuthenticationProvider() {

}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Authentication result = null;
AuthenticationException exception = null;
try {
result = primaryProvider.authenticate(authentication);
} catch (AuthenticationException e) {
exception = e;
for (ActiveDirectoryLdapAuthenticationProvider secondaryProvider : secondaryProviders) {
try {
result = secondaryProvider.authenticate(authentication);
if (result.isAuthenticated()) {
break;
}
} catch (AuthenticationException e1) {
exception = e;
}
}
}
if (result == null || !result.isAuthenticated()) {
throw exception;
}

return result;
}

我有全局异常处理程序,如下所示。

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler({NoPermissionException.class})
@ResponseBody
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public Map<String, String> noPermission(NoPermissionException e) {
return createErrorResponse(e, "Don't have permissions");
}

@ExceptionHandler({Exception.class})
@ResponseBody
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> exceptionInProcessing(Exception e) {
return createErrorResponse(e, "Unable to process. Unknown error occurred: " + e.getMessage());
}

private Map<String, String> createErrorResponse(Exception e, String errorMessage) {
Map<String, String> errorResponse = new HashMap<>();
errorResponse.put("message", errorMessage);
errorResponse.put("reason", e.toString());
return errorResponse;
}
}

当“authenticate”函数内部抛出异常时,不会调用全局异常处理程序。对于所有其他异常,都会调用它。我想捕获全局异常处理程序中的异常并返回自定义错误消息。我怎样才能做到这一点?任何帮助表示赞赏。提前致谢。

最佳答案

GlobalExceptionHandler用于 Controller 异常处理程序,但 AuthenticationProvider仍在过滤器中,如果您想处理 AuthenticationException ,你需要处理它才能实现AuthenticationEntryPoint并覆盖 commence方法。

public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException

AuthenticationExceptionAccessDeniedException已被ExceptionTranslationFilter处理。你只需要注入(inject) AuthenticationEntryPointAccessDeniedHandler (处理 AccessDeniedException )

或者你可以在过滤器中捕获这些异常,然后在文件管理器中处理它,例如 AuthenticationFailureHandlerAbstractAuthenticationProcessingFilter

关于java - 捕获 AuthenticationProvider 中抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43981413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com