HttpOnly cookie 不随请求传递

时间:2021-05-10 20:23:26

标签: angular spring authentication cookies httponly

我正在尝试将令牌存储在 HttpOnly cookie 中,但是我不确定如何实现。首先,我的 SpringBoot 服务器是这样返回它们的

@PostMapping("/sign-in")
fun signIn(@RequestBody request: SignInRequest, response: HttpServletResponse): ResponseEntity<SignInResponse> {
    val signInResponse = signInService.signIn(request);
    val cookie = Cookie("Authorization", signInResponse.accessToken)
    cookie.isHttpOnly = true
    response.addCookie(cookie)
    return ResponseEntity.ok(signInResponse)
}

然后,在我的 Angular 应用程序中,我调用了这个 API

  ngOnInit() {
    this.httpClient.post("http://localhost:8081/api/auth/sign-in", {
      email: "user@user.com",
      password: "user"
    }).subscribe(res => {
      console.log(res)
    })
  }

似乎工作正常,当我在浏览器中转到网络选项卡时,可以看到 Cookie

enter image description here

但是,然后我尝试调用另一个端点,cookie 没有通过

callWithCredentials() {
    this.httpClient.get(
      "http://localhost:8081/api/test",
      { withCredentials: true }
    ).subscribe(res => {
      console.log(res)
    })
  }

enter image description here

1 个答案:

答案 0 :(得分:0)

跨源

调用托管在 localhost 上的 Web API 很可能是跨源请求,尽管您的前端和后端在同一台机器上(“localhost”)。即使您配置了跨域,某些浏览器也不支持具有“locahost”源的 javascript 的跨域。

在这种情况下,您需要在 Springboot 应用程序中配置“Access-Control-Allow-Origin”和“Access-Control-Allow-Credentials”。如果您选择 Chrome 浏览器进行测试,请在“localhost”以外的某些地方使用您的 javascript。

调试

转到“网络”选项卡并检查响应的标头。看看你的响应头中是否有这些。

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://example.com

更改 Javascript 来源

如果您使用的是 Windows,请修改 host 文件。将“example.com”等域解析为“127.0.0.1”。

然后您可以打开“http://example.com:8080”将javascript来源从localhost更改为“example.com”

Springboot 中的 CORS 配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /* Allow cookies */
        corsConfiguration.setAllowCredentials(true);
        /* This is your javascript origin */
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);

    }
// ...

}


这里有一个简短的提醒。

<块引用>

公共 CorsConfiguration setAllowedOriginPatterns(@Nullable 列出 allowedOriginPatterns) 支持通过通配符模式声明的来源的 setAllowedOrigins(java.util.List) 的替代方法。与支持特殊值“”的 allowedOrigins 相比,此属性允许更灵活的模式,例如“https://.domain1.com”。此外,它始终将 Access-Control-Allow-Origin 响应标头设置为匹配的源,从不设置为“*”,也不设置为任何其他模式,因此可以与设置为 true 的 setAllowCredentials(java.lang.Boolean) 结合使用.

Reference

确保您使用的是最新版本,以便您可以使用 .addAllowedOriginPattern("*"),否则您必须在您的 javascript 域中明确使用 .addAllowedOrigin("http://example.com:8080")