【问题标题】:React App + Spring Boot - JWT auth token inside a cookie is not set in ChromeReact App + Spring Boot - cookie 中的 JWT 身份验证令牌未在 Chrome 中设置
【发布时间】:2020-07-04 06:37:18
【问题描述】:

我正在尝试在我的 react 应用程序发出登录请求后将 Spring Boot 配置为包含 JWT 身份验证令牌的 set-cookie,然后期望浏览器会自动将此 cookie 设置为由指定的所有请求饼干路径。这种行为在我朋友的环境中没问题 - 相同的代码、Chrome 浏览器、不同的机器。我试过清除node_modules,mvn clean install,也试过不同的浏览器Chrome和FireFox,都没有成功。

这是所有相关代码(如果我遗漏了其他重要的东西,请告诉我)

  • React 正在 localhost:3000 上运行
  • Spring Boot 在 localhost:8080 上运行
  • package.json中有一个代理

    “代理”:“http://localhost:8080”,

为了测试身份验证流程,我们从登录表单 (react) 发出登录请求,请求成功代理到端口 8080,并且来自服务器的响应成功返回 JWT 令牌作为授权饼干。 cookie 被指定到/api 路径。网络请求如下图所示:

登录后,react 应用程序立即向后端发出第二个 HTTP 请求,但服务器上的断点显示没有 cookie 作为此请求的一部分从浏览器传递。请求是http://localhost:3000/api/user。

在前端,我们使用fetch 发出请求,它看起来像这样:

fetch("/api/user, {
    credentials: "same-origin"
  })

仅作为附加上下文,这是我们在成功登录后从服务器返回原始 cookie 的方式:

@PostMapping("/signin")
    public ResponseEntity signin(@RequestBody AuthenticationRequest data, HttpServletResponse response) {
        try {
            String username = data.getUsername();
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
            User user = (User) authentication.getPrincipal();
            String token = jwtTokenProvider.createToken(user);
            final Cookie cookie = new Cookie("auth", token);
            cookie.setSecure(!environment.acceptsProfiles(Profiles.of("dev")));
            cookie.setHttpOnly(true);
            cookie.setMaxAge(Integer.MAX_VALUE);
            cookie.setPath("/api");
            response.addCookie(cookie);

            return ok(buildUserResponseObject(user));
        } catch (AuthenticationException e) {
            throw new BadCredentialsException("Invalid username/password supplied");
        }
    }

我们的方法有什么问题吗?是什么阻止了我的浏览器传递 auth cookie?

【问题讨论】:

    标签: reactjs spring-boot google-chrome cookies setcookie


    【解决方案1】:

    这太尴尬了……

    问题是这一行

    cookie.setSecure(!environment.acceptsProfiles(Profiles.of("dev")));
    

    !environment.acceptsProfiles(Profiles.of("dev")) 被评估为 true 并且它导致 cookie 仅在连接安全的情况下才被传递,这不是因为它是本地主机。谜团解开了。

    【讨论】:

    • 我遇到了同样的问题,我创建了一个和你一样的 cookie,它出现在 header set-cookie 中,但不在应用程序 cookie 中。我该如何解决这个问题,我的问题可能是什么?我正在使用反应 axios。
    猜你喜欢
    • 2020-10-24
    • 2018-02-27
    • 2020-08-23
    • 1970-01-01
    • 2019-04-17
    • 2022-10-05
    • 2020-04-23
    • 2018-12-24
    • 2019-03-31
    相关资源
    最近更新 更多