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

Vaadin 23集成Spring Security与Keycloak:登录后无法重定向至原页面

解决Vaadin 23 + Spring Security + Keycloak登录后无法重定向至原始页面的问题

问题根源

登录后始终跳转首页,核心原因是用户发起登录前的原始请求信息未被正确保存或恢复。结合你的代码,主要是无状态认证配置干扰了session存储,以及OAuth2登录流程缺少请求保存的必要配置。

具体修改步骤

1. 调整无状态认证配置,排除OAuth2相关端点

你启用的Vaadin无状态认证会强制所有请求使用JWT而不依赖session,但OAuth2登录流程需要临时用session保存原始请求。修改configure(HttpSecurity http)中的setStatelessAuthentication调用,排除OAuth2相关端点:

setStatelessAuthentication(http, 
    new SecretKeySpec(Base64.getDecoder().decode(jwtAuthSecret), JwsAlgorithms.HS256), 
    "com.example",
    "/oauth2/**", "/login", "/logout", "/session-expired");

这些端点将允许使用session,确保原始请求能被正常保存。

2. 配置OAuth2请求解析器,启用原始请求保存

在oauth2Login配置中添加SavedRequestAwareAuthorizationRequestResolver,它会自动保存用户登录前的原始请求路径,登录成功后恢复重定向:

.oauth2Login(oauth2Login ->
        oauth2Login
                .clientRegistrationRepository(clientRegistrationRepository)
                .userInfoEndpoint(userInfoEndpoint ->
                        userInfoEndpoint
                                .userAuthoritiesMapper(authoritiesMapper)
                )
                .loginPage("/login")
                // 添加请求解析器,保存原始请求
                .authorizationRequestResolver(new SavedRequestAwareAuthorizationRequestResolver(
                        clientRegistrationRepository,
                        new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, "/oauth2/authorization")
                ))
                .successHandler(new KeycloakVaadinAuthenticationSuccessHandler(profileService))
)

3. 确认自定义成功处理器的逻辑

你的KeycloakVaadinAuthenticationSuccessHandler已正确继承VaadinSavedRequestAwareAuthenticationSuccessHandler,且在最后调用了super.onAuthenticationSuccess——这个顺序是对的:先完成用户信息初始化,再交给父类处理重定向,确保原始请求的恢复逻辑生效,无需修改。

4. 验证WebSecurity忽略配置

当前的忽略配置未覆盖必要路径,保持现状即可:

web.ignoring().antMatchers("/session-expired", "/images/*", "/login", "/favicon.ico");

完成以上修改后,用户访问需登录的视图时,系统会保存原始路径,登录成功后自动重定向至该页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:45:54