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

Spring Boot JWT认证成功后始终重定向至根路径问题求助

解决JWT认证后重定向到"/"的问题

我帮你排查了代码里的几个关键点,这个重定向问题主要是因为默认的认证成功处理器触发了表单登录的重定向逻辑,下面是具体的修复步骤:

1. 修复JwtAuthenticationTokenFilter的successfulAuthentication方法

你当前的代码调用了super.successfulAuthentication(),而父类的这个方法会使用SavedRequestAwareAuthenticationSuccessHandler——这是为表单登录设计的,它会自动重定向到之前保存的请求路径(如果没有的话就默认到"/")。

修改这个方法,去掉父类调用,直接手动将认证信息存入上下文并继续过滤器链:

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    // 将认证后的用户信息存入SecurityContext
    SecurityContextHolder.getContext().setAuthentication(authResult);
    // 继续执行后续的过滤器和请求处理,不要触发重定向
    chain.doFilter(request, response);
}

2. 确保自定义成功处理器不做重定向

你设置了JwtSuccessHandler,但如果它的实现没处理好,也可能导致问题。让它的onAuthenticationSuccess方法什么都不做,直接放行:

public class JwtSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 无需任何操作,让请求继续流向目标接口
    }
}

3. 验证AuthenticationEntryPoint的实现

如果你的JwtAuthenticationEntryPoint是处理未认证请求的,要确保它返回的是401错误而不是重定向,避免未认证时的不必要跳转:

public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Invalid or missing JWT Token");
    }
}

4. 检查Security配置的细节

你的JwtSecurityConfig里已经设置了sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS),这个是正确的(JWT认证不需要会话),保持这个配置即可。

做完这些修改后,再携带Token请求/rest/hello,应该就会正常访问目标接口,不会再重定向到"/"了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:38:05