【问题标题】:Angular 8 get "Set-Cookie" header from HttpResponseAngular 8 从 HttpResponse 获取“Set-Cookie”标头
【发布时间】:2020-02-14 11:56:28
【问题描述】:

我有以下 Java Spring REST API 方法:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity login(@RequestBody LoginRequest request) {
    request.getSession(true);
    LoginResponse res = this.authService.login(request);
    return new ResponseEntity<>(res, HttpStatus.OK);
}

当使用 Postman 或从 FireFox 浏览器调用时,我可以清楚地看到“Set-Cookie”标题:

然而,当我使用 console.log 在 Angular 中打印响应时,我看不到这个标题:

这是 Angular 中的 REST 调用:

this.http.post<Login>(this.url, this.loginRequest, {
  headers: AuthService.getHeaders(),
  observe: 'response',
  withCredentials: true
}).subscribe(
  response => {
    console.log(response);
});

我确实按照建议在请求调用中添加了withCredentials: trueobserve: 'response',我确实得到了整个响应,但没有cookie。 我想要做的是在成功登录后获取一个 cookie,之后它将与任何请求一起交付以在服务器中进行身份验证。

感谢您的帮助!

【问题讨论】:

  • 您的 Spring REST API 使用 Spring Security?你用的是哪个版本的 Spring boot/security?
  • 没有 Spring Security,也没有 Spring Boot。简单的旧 Spring MVC :)
  • 您是否尝试过使用内置的 JS 功能来获取页面 cookie? (例如document.cookie)这很可能是浏览器的一项安全功能,用于防止从其他域窃取cookie,并且不会传递给JavaScript(此外,某些cookie值将无法访问,因为它们具有httponly设置)。
  • 我现在试过了,结果是null :(

标签: java angular spring typescript cookies


【解决方案1】:

如果不是https,浏览器似乎不会将cookie共享给客户端。我必须遵循这个guide 才能在 https 模式下为应用程序提供服务,然后我才能在服务器端看到 cookie。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2021-10-21
    • 2019-05-18
    • 2014-02-26
    相关资源
    最近更新 更多