gpt4 book ai didi

java - 捕获 AuthenticationProvider 中抛出的异常

转载 作者:搜寻专家 更新时间:2023-10-31 20:32:29 26 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还在filter中,如果你想处理AuthenticationException,你需要处理它以实现 AuthenticationEntryPoint 并覆盖 commence 方法。

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

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

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

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

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