【发布时间】: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