我正在尝试将令牌存储在 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
但是,然后我尝试调用另一个端点,cookie 没有通过
callWithCredentials() {
this.httpClient.get(
"http://localhost:8081/api/test",
{ withCredentials: true }
).subscribe(res => {
console.log(res)
})
}
答案 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
如果您使用的是 Windows,请修改 host
文件。将“example.com”等域解析为“127.0.0.1”。
然后您可以打开“http://example.com:8080”将javascript来源从localhost更改为“example.com”
@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
确保您使用的是最新版本,以便您可以使用 .addAllowedOriginPattern("*")
,否则您必须在您的 javascript 域中明确使用 .addAllowedOrigin("http://example.com:8080")
。