You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.5整合SAML、OIDC与数据库认证及会话跳转问题咨询

问题根因

你当前仅为httpBasic配置了自定义AuthenticationEntryPoint,仅能处理认证流程抛出的AuthenticationException异常。会话过期触发的是会话管理相关的InvalidSessionStrategy/SessionInformationExpiredStrategy,不会走你配置的认证入口逻辑,因此不会触发跳转。

解决方案

1. 配置会话过期/挤下线的跳转策略

修改你现有的sessionManagement配置,根据当前启用的认证模式跳转到对应登录入口,同时兼容AJAX异步请求的场景:

http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        // 会话无效(过期/未登录访问受限路径)处理逻辑
        .invalidSessionStrategy((request, response) -> {
            String redirectPath = !samlAuth ? "/ui/oidc/" : "/ui/saml/";
            String redirectUrl = request.getContextPath() + redirectPath;
            // 异步请求返回401和提示,避免前端无法识别302跳转
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"会话已过期,请重新登录\"}");
            } else {
                response.sendRedirect(redirectUrl);
            }
        })
        .sessionFixation().migrateSession()
        // 可选:限制同账号同时在线数,配置挤下线处理逻辑
        .maximumSessions(1)
        .expiredSessionStrategy(event -> {
            HttpServletRequest request = event.getRequest();
            HttpServletResponse response = event.getResponse();
            String redirectPath = !samlAuth ? "/ui/oidc/" : "/ui/saml/";
            String redirectUrl = request.getContextPath() + redirectPath;
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"账号已在其他设备登录,请重新登录\"}");
            } else {
                response.sendRedirect(redirectUrl);
            }
        });

2. 补全认证入口点的兜底逻辑

你当前SAML分支的AuthenticationEntryPoint仅处理/ui/saml/路径的请求,其他受限路径触发认证异常时无响应,补充兜底逻辑:

.httpBasic().authenticationEntryPoint((request, response, authException) -> {
    String uri = request.getRequestURI();
    // 所有受限路径访问触发认证异常时都走对应入口点
    if (uri.startsWith("/ui/saml/") || uri.startsWith("/api/v1/")) {
        samlEntryPoint.commence(request, response, authException);
    } else {
        response.sendRedirect(request.getContextPath() + "/ui/app/");
    }
});

OIDC分支也可以参照上述逻辑补全AuthenticationEntryPoint的兜底规则,避免部分路径无响应。

3. 校验自定义过滤器逻辑

检查你自定义的expiredSessionFilter,确保没有吞掉会话相关异常、没有提前返回响应拦截了上层的会话策略处理,仅保留业务逻辑即可。

内容的提问来源于stack exchange,提问作者Grv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:36:07