Vaadin 24登录后始终重定向至根URL,需跳转至来源页
解决Vaadin 24登录后跳转至来源URL的问题
问题原因
当前配置中super.configure(http)的调用顺序不合理,导致Vaadin的默认安全配置覆盖了自定义的认证成功处理器设置,使得Spring Security无法正确保存并恢复原始请求路径。
修正安全配置
调整配置执行顺序,先初始化父类的Vaadin安全机制,再添加自定义规则,确保认证成功处理器生效:
@EnableWebSecurity @Configuration public class SecurityConfig extends VaadinWebSecurity { private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class); @Override protected void configure(HttpSecurity http) throws Exception { logger.debug("Security Config set..."); // 先执行父类配置,初始化Vaadin核心安全机制 super.configure(http); // 配置静态资源与登录页的公开访问权限 http.authorizeHttpRequests(auth -> auth .requestMatchers( AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/icons/*.png"), AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/img/*.png") ).permitAll() .requestMatchers( AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/login*") ).permitAll() ); // 指定自定义登录视图 setLoginView(http, LoginView.class); // 配置认证成功处理器,自动恢复原始请求跳转 http.formLogin(formLogin -> formLogin.successHandler(new VaadinSavedRequestAwareAuthenticationSuccessHandler()) ); } }
手动导航登录场景的补充处理
如果用户是主动点击按钮跳转至登录页(而非被Spring Security自动重定向),需要手动传递来源路径参数:
- 在触发登录跳转的代码中,携带当前页面路径:
// 获取当前页面的路径 String currentPath = UI.getCurrent().getLocation().getPath(); // 导航到登录页并携带redirect参数 UI.getCurrent().navigate(LoginView.class, Map.of("redirect", currentPath));
- 在
LoginView中处理登录成功后的跳转逻辑:
public class LoginView extends VerticalLayout { public LoginView(AuthenticationManager authenticationManager) { LoginForm loginForm = new LoginForm(); loginForm.addLoginListener(event -> { try { Authentication auth = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(event.getUsername(), event.getPassword()) ); SecurityContextHolder.getContext().setAuthentication(auth); // 获取redirect参数,默认跳转根路径 String redirect = getRouteParameters().get("redirect").orElse("/"); UI.getCurrent().navigate(redirect); } catch (AuthenticationException e) { loginForm.setError(true); } }); add(loginForm); setSizeFull(); setAlignItems(Alignment.CENTER); setJustifyContentMode(JustifyContentMode.CENTER); } }
验证说明
- 当访问需要权限的页面时,Spring Security会自动重定向到登录页,并在会话中保存原始请求,登录成功后自动跳转回原页面。
- 手动跳转登录页的场景,需确保
redirect参数正确传递,登录成功后按参数指定路径跳转。
内容的提问来源于stack exchange,提问作者padmalcom
相关产品推荐
相关产品推荐

