在 spring boot 中捕获 sso 登录异常,核心做法是配置一个全局异常处理器(实现 handlerexceptionresolver 或添加 @controlleradvice),并在其中拦截特定的 sso 客户端抛出的异常类。当用户未登录或 token 失效时,sso 过滤器会抛出如 ssoexception 或 authenticationexception,全局处理器捕获这些异常后,可统一返回 json 错误信息或直接重定向到 sso 登录页。

如何识别并拦截 SSO 抛出的特定异常?
要拦截 SSO 异常,首先需要知道你的 SSO 客户端库(如 Apereo CAS Client、Spring Security OAuth2 或自研 SDK)在认证失败时具体抛出什么异常。通常,这些异常继承自 RuntimeException 或特定的 SecurityException。在全局异常处理器中,通过 @ExceptionHandler 注解指定这些异常类型,即可精准捕获。

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class GlobalSSOExceptionHandler {
// 假设 SSO 客户端抛出的特定异常
@ExceptionHandler(SSOAuthenticationException.class)
public ModelAndView handleSSOException(HttpServletRequest request, SSOAuthenticationException ex) {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/sso/login?error=auth_failed");
return mv;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleGenericException(HttpServletRequest request, Exception ex) {
ModelAndView mv = new ModelAndView();
mv.addObject("errorMessage", "系统内部错误: " + ex.getMessage());
mv.setViewName("error/500");
return mv;
}
}上述代码展示了两个关键方法:第一个专门处理 SSO 认证异常,将其重定向到登录页;第二个作为兜底,处理其他所有未捕获的异常。开发者需根据实际使用的 SSO 库替换 SSOAuthenticationException 为实际的异常类名。
如何在异常处理中区分 API 请求和普通页面请求?
在实际应用中,前端可能同时存在普通 HTML 页面请求和 AJAX/API 调用。SSO 异常发生时,对于页面请求应重定向到登录页,而对于 API 请求则应返回 HTTP 401 状态码及 JSON 错误体。这可以通过检查请求头中的 Accept 字段或 X-Requested-With 来实现。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class HybridSSOExceptionHandler {
@ExceptionHandler(SSOAuthenticationException.class)
public Object handleSSOException(HttpServletRequest request, SSOAuthenticationException ex) {
String accept = request.getHeader("Accept");
boolean isApiRequest = (accept != null && accept.contains("application/json"))
|| "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
if (isApiRequest) {
Map<String, String> errorBody = new HashMap<>();
errorBody.put("error", "unauthorized");
errorBody.put("message", "SSO authentication failed");
return new ResponseEntity<>(errorBody, HttpStatus.UNAUTHORIZED);
} else {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/sso/login?source=" + request.getRequestURI());
return mv;
}
}
}这段代码通过判断请求类型,实现了差异化响应。如果是 API 请求,返回 401 JSON;如果是页面请求,重定向到登录页并携带原始请求 URI,以便登录后能跳回原页面。这种处理方式确保了前后端分离架构下的用户体验一致性。
如果 SSO 服务器宕机,全局异常处理该如何降级?
当 SSO 服务器不可用时,SSO 客户端可能会抛出连接超时或网络异常。此时,全局异常处理器应能捕获这些底层异常,并提供降级策略,例如允许用户以本地缓存凭证访问部分非敏感资源,或返回友好的维护提示。这需要捕获更广泛的异常类型,如 ConnectTimeoutException 或 SocketException。
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.net.ssl.SSLHandshakeException;
import java.net.ConnectException;
@ControllerAdvice
public class DegradationSSOExceptionHandler {
@ExceptionHandler({ConnectException.class, SSLHandshakeException.class, SocketException.class})
public ModelAndView handleSSODown(HttpServletRequest request, Exception ex) {
// 记录日志
System.err.println("SSO Server unreachable: " + ex.getMessage());
ModelAndView mv = new ModelAndView();
mv.addObject("fallbackMessage", "SSO 服务暂时不可用,请使用备用登录方式或稍后重试。");
mv.setViewName("error/sso_down");
return mv;
}
}此段代码演示了针对网络层异常的降级处理。通过捕获具体的网络异常,可以避免将原始的堆栈信息暴露给前端,而是展示一个经过设计的友好错误页面。开发者可根据业务需求,在此处集成本地数据库验证或其他备用认证机制,以实现高可用性的登录流程。


















