问题描述
所以我基本上使用 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 {}