【问题标题】:RedisHttpSession is creating different sessionIds for requests from the same browserRedisHttpSession 正在为来自同一浏览器的请求创建不同的 sessionId
【发布时间】:2021-01-15 14:44:05
【问题描述】:

所以我基本上使用RedisHttpSession 进行会话管理。我创建了这个登录 API,它在登录成功时将 Staff 对象存储在会话中。 request.getSession().setAttribute("staff", staff); 在其他 API 中,我验证是否有有效员工登录,如果没有,我将他们重定向到登录页面。 Staff staff = (Staff) request.getSession().getAttribute("staff"); 现在,当我用 Postman 测试整个场景时,它按预期工作,但是我将它放在服务器上,request.getSession().getId() 在每个请求中都不同。

我注意到的另一件事是,当我从 Postman 发送请求时,我看到 cookie 被存储,但浏览器上没有 cookie。

为什么每个请求中的 sessionId 都不一样?我该如何解决这个问题?

【问题讨论】:

  • 好吧,上面的代码是关于创建 RedisClient/Connection 的,而您的问题是关于 HttpSession - 这更多地与 Spring 有关,两者都不相关。您应该查看根据请求/响应处理 HttpSession 管理的代码。

标签: java spring-boot httpsession spring-session lettuce


【解决方案1】:

HttpSession 每次都创建一个新的 SessionId,因为 cookie 没有存储在浏览器中。为了解决这个问题,我创建了一个新的@Configuration

@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedOrigins("http://localhost:4200", "https://sub.domain.com",
                                "https://sub2.domain.com")
                        .allowedHeaders("*").allowCredentials(true);
            }
        };
    }
}

这将使浏览器保存 cookie,但这本身并不足以让一切正常运行。您还必须在前端修改您的请求。将withCredentials: true 添加到您的请求中,例如:

    const httpOptions = {
      params: new HttpParams({ encoder: new CustomHttpUrlEncodingCodec() })
        .set('fileType', fileType.toString())
        .set('jobDetailsID', jobDetailsID),
      headers: new HttpHeaders().set('ngsw-bypass', 'true'),
      withCredentials: true
    }

或者您可以创建一个HttpInterceptor 并处理所有请求:

@Injectable()
export class CustomInterceptor implements HttpInterceptor { 

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2017-06-25
    相关资源
    最近更新 更多