【问题标题】:Wrong credentials in REST fetch with multiple users per session每个会话有多个用户的 REST 获取中的错误凭据
【发布时间】:2020-01-08 12:06:02
【问题描述】:

我有一个通过 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
    }

【问题讨论】:

  • 如何发送凭证信息?是带有会话 ID 的 cookie 还是类似的东西?
  • 我认为你在技术实现方面做不到。

标签: reactjs typescript rest rxjs fetch


【解决方案1】:

我的解决方案(只是因为我也有一个 websocket 连接才有效):

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2011-08-29
    • 2021-04-09
    • 1970-01-01
    • 2014-02-18
    • 2020-08-28
    • 2011-04-24
    相关资源
    最近更新 更多