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

Spring Security未认证访问时如何在登录URL追加目标跳转参数

核心问题原因

你混淆了SavedRequestAwareAuthenticationSuccessHandler中targetUrlParameter配置的作用:该参数仅作用于登录认证成功后的逻辑,Spring Security会从登录提交的请求中读取对应参数的值作为跳转目标,不会自动在重定向到登录页的环节为你追加该参数。

要实现未登录访问受保护资源时,登录页地址自动携带redirect参数,需要自定义登录认证入口的重定向逻辑,配置步骤如下:

步骤1:自定义认证入口类

继承LoginUrlAuthenticationEntryPoint,重写重定向地址生成逻辑,追加原请求路径作为redirect参数:

import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

    public CustomAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, 
                                                     HttpServletResponse response, 
                                                     AuthenticationException exception) {
        // 拼接原请求完整路径
        StringBuilder originPath = new StringBuilder(request.getRequestURI());
        if (request.getQueryString() != null) {
            originPath.append("?").append(request.getQueryString());
        }
        // 对路径编码避免特殊字符异常
        String encodedOriginPath = URLEncoder.encode(originPath.toString(), StandardCharsets.UTF_8);
        return getLoginFormUrl() + "?redirect=" + encodedOriginPath;
    }
}

步骤2:在安全配置中注册自定义入口

修改你的WebSecurityConfiguration中的configure方法,添加异常处理的认证入口配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/login**", "/actuator/**").permitAll()
        .anyRequest().authenticated()
        .and()
        // 新增自定义认证入口配置
        .exceptionHandling()
        .authenticationEntryPoint(new CustomAuthenticationEntryPoint("/login"))
        .and()
        .formLogin().loginPage("/login").permitAll().successHandler(authenticationSuccessHandler())
        .failureHandler(authenticationFailureHandler())
        .and()
        .logout().logoutSuccessUrl("/login").permitAll()
        .and()
        .rememberMe().key(token).tokenValiditySeconds(validity)
        .userDetailsService(service)
        .and()
        .csrf().disable();
}

注意事项

上线前建议增加redirect参数的合法性校验,比如校验跳转路径是否为本站内部路径,避免出现开放重定向漏洞,被恶意利用跳转到外部钓鱼网站。

内容的提问来源于stack exchange,提问作者Joaquín L. Robles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:39:03