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

Spring Boot OAuth2 Client:如何实现浏览器关闭后保持用户登录(Google OAuth2)

解决Spring Boot OAuth2登录后浏览器关闭会话丢失问题

核心原因

默认情况下,Spring Security生成的JSESSIONID Cookie是会话级的,浏览器关闭后会自动删除,导致用户重新打开浏览器需要重新登录。要实现持久化登录,需要修改Cookie的持久化属性,同时可选地将会话数据持久化到服务器端(如Redis)。


方法一:配置持久化会话Cookie

通过Spring Security或全局配置,修改会话Cookie的有效期,让浏览器关闭后保留Cookie。

1. 在SecurityFilterChain中配置会话Cookie

修改你的filterChain Bean,添加sessionManagement配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/",  "/oauth/**").permitAll()
                    .anyRequest().authenticated()
            )
            .oauth2Login(oauth2Login -> oauth2Login
                    .userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint
                            .userService(googleOAuth2UserService)
                    )
                    .successHandler((request, response, authentication) -> {
                        GoogleOAuth2User googleOAuth2User = (GoogleOAuth2User) authentication.getPrincipal();
                        userService.processOAuthPostLogin(googleOAuth2User);
                        response.sendRedirect("http://localhost:3000");
                    })
            )
            .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .sessionFixation().migrateSession()
                    .cookieConfig(cookie -> cookie
                            .maxAge(Duration.ofDays(7)) // 设置Cookie有效期为7天
                            .httpOnly(true) // 禁止前端JS读取Cookie,防XSS
                            .secure(false) // HTTPS环境请改为true
                    )
            );

    return http.build();
}

2. 全局配置(可选)

也可以通过application.yml或application.properties全局设置会话Cookie:

server:
  servlet:
    session:
      cookie:
        max-age: 7d # 有效期7天
        http-only: true
        secure: false # 生产环境HTTPS务必设为true

方法二:用Spring Session持久化会话到Redis(分布式场景推荐)

如果你的应用是多实例部署,或者需要服务器端持久化会话数据,推荐使用Spring Session将会话存储到Redis。

1. 添加依赖

在pom.xml中加入Redis和Spring Session依赖:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 配置Redis和Spring Session

修改application.yml:

spring:
  redis:
    host: localhost
    port: 6379
    # 若Redis有密码,添加 password: your-redis-password
  session:
    store-type: redis
    timeout: 7d # 会话超时时间,需与Cookie有效期一致
    redis:
      flush-mode: on_save
      namespace: spring:session
server:
  servlet:
    session:
      cookie:
        max-age: 7d
        http-only: true
        secure: false

注意事项

  • secure: true仅在HTTPS环境下启用,否则Cookie无法被浏览器保存。
  • http-only: true是必要的安全配置,避免Cookie被前端脚本窃取。
  • Cookie有效期可根据业务需求调整(如30天、1天等),但过长的有效期会增加安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:37:26