【发布时间】:2021-01-05 18:00:50
【问题描述】:
我有一个 Angular 应用程序和一个 Spring Boot 后端。我必须将 cookie 从浏览器发送到后端。
现在的问题是:当我使用 ng serve 时,一切都按预期工作。 cookie 被发送并可以由后端处理。当我使用 ng build --no-aot 构建我的应用程序时,浏览器不会发送任何 cookie。
注意:我们处于跨域设置中。
这是我的 Spring Cors 配置。我明确定义了我的起源。我没有使用* 作为配置:
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("http://127.0.0.1:8080");
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"));
corsConfiguration.addAllowedHeader("origin");
corsConfiguration.addAllowedHeader("content-type");
corsConfiguration.addAllowedHeader("accept");
corsConfiguration.addAllowedHeader("ct-remote-user");
corsConfiguration.addAllowedHeader("shared-secret");
corsConfiguration.addAllowedHeader("cookie");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new
UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
我的 Angular 应用程序中的 Http 客户端使用 {withCredentials: true} 作为选项:
get(requestPath: string, params?: HttpParams, responseType?): Observable<any> {
const options = {headers: this.getDefaultHeaders(), withCredentials: true, params, responseType: responseType};
return this.httpClient.get(requestPath, options);
}
当我在浏览器中检查请求时,预检请求会发送以下内容:
OPTIONS /pathToRessource HTTP/1.1
Host: localhost:9084
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Access-Control-Request-Method: GET
Origin: http://127.0.0.1:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Sec-Fetch-Dest: empty
Referer: http://127.0.0.1:8080
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
我的服务器会这样回应:
Request-Id: fe605923-1f0f-40c7-bf5e-a575903df450
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://127.0.0.1:8080
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,HEAD
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 0
Date: Wed, 30 Dec 2020 10:18:16 GMT
Keep-Alive: timeout=60
Connection: keep-alive
所以我建议正确配置 CORS。当我现在发送我的 GET 请求时,请求中不包含 cookie,并且由于缺少 Cookie 标头,服务器以 403 响应(这是正确的行为)。有什么建议我做错了吗?我在问这个问题之前搜索了问题,但所有解决方案都建议正确配置 CORS。我想这里就是这种情况。
【问题讨论】:
标签: angular spring-boot cookies cors