reactjs - 每个会话有多个用户的 REST 获取中的错误凭据
问题描述
我有一个通过 REST 获取数据的 web 应用程序(使用 react、redux)。只要我每个会话只登录一个用户,一切都可以正常工作。如果我使用同一个浏览器一次登录多个用户,则在 BE(带有 spring 的 java)中会收到错误的主体(始终是最新登录用户的主体)。
如何为每个用户发送正确的凭据?
FE:
public restPost(url: string, request: any): Rx.Observable<any> {
return Rx.Observable.create(
(observer: Rx.Observer<any>) => {
fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
}).then((response: Response) => {
// handle response
})
.catch(error => observer.error(error));
}
);
}
是:
@RequestMapping(value="/test", method = RequestMethod.POST)
@CrossOrigin(origins = "*")
public ResponseEntity<Test> test(@RequestBody TestRequest testReq, HttpServletResponse response, @AuthenticationPrincipal Principal principal) {
// at this point the principal.getName() has the name of the latest logged in user
// return the response
}
解决方案
我的解决方案(仅工作,因为我也有一个 websocket 连接):
在 FE 的 REST 标头中添加了不记名令牌:
headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: header ? ('Bearer ' + header.token) : '' }
在 BE 中,我将带有令牌的映射保存到主体,然后我可以访问该映射以获取 REST 消息
推荐阅读
- javascript - 刷新和访问令牌的交换授权代码 - 错误 400
- java - 使用缓存对对象的 ArrayList 进行排序
- php - IIS URL 重写重定向到图像以跟踪电子邮件视图
- html - 如何在 Google 表格中使用 REEXTRACT 来隔离 GCLID?
- overloading - 不能重载 Raku 中的 >> 运算符
- html - 表格单元格,换行的文本,适合内容的宽度,删除额外的右手空白
- amazon-web-services - AWS:具有弹性 IP 的 ECS 服务
- reactjs - 关于 React.js 组件结构的概念问题
- python - 删除具有“未知”类别的电影
- javascript - 从 React 应用程序更新非 React Dom 元素的 CSS 属性