首页 > 解决方案 > 每个会话有多个用户的 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
    }

标签: reactjstypescriptrestrxjsfetch

解决方案


我的解决方案(仅工作,因为我也有一个 websocket 连接):

  • 在 FE 的 REST 标头中添加了不记名令牌:

    headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    Authorization: header ? ('Bearer ' + header.token) : ''
                }
    
  • 在 BE 中,我将带有令牌的映射保存到主体,然后我可以访问该映射以获取 REST 消息


推荐阅读