java - RedisHttpSession 正在为来自同一浏览器的请求创建不同的 sessionId
问题描述
所以我基本上RedisHttpSession
用于会话管理。我创建了这个登录 API,它Staff
在登录成功时将对象存储在会话中。request.getSession().setAttribute("staff", staff);
在其他 API 中,我验证是否有有效的员工登录,如果没有,我将他们重定向到登录页面。Staff staff = (Staff) request.getSession().getAttribute("staff");
现在,当我使用 Postman 测试整个场景时,它按预期工作,但是,我将它放在服务器上,并且request.getSession().getId()
每个请求都不同。
我注意到的另一件事是,当我从 Postman 发送请求时,我看到 cookie 被存储,但浏览器上没有 cookie。
为什么每个请求中的 sessionId 都不一样?我该如何解决这个问题?
解决方案
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 {}
推荐阅读
- javascript - React Hooks & UseEffect 不使用 socketIO 数据更新显示。只渲染数组中的元素
- r - 使用have::labelled动态创建价值标签,跟进
- php - 如何将附加参数传递给 Laravel 登录控制器中的 handleProviderCallback 函数
- python - PyMongo 查询问题:递增嵌套的 dict 条目
- css - 这个序列的第 n 项是什么?
- c# - BizTalk 自定义管道组件 - 读取 JSON 节点值并提升属性
- terraform - 无服务器部署到不同的 AWS 账户
- javascript - React js:将 props 传递给 React Router 的 Link 组件
- u-boot - U-boot:如何检查 tftp 命令是否成功将映像加载到 ram 中?
- maven - maven jar 在一个 war 模块中部署了两次,attachClasses 设置为 true