在CORS应用程序中使用Cookie

时间:2018-07-22 05:00:40

标签: angular rest cors xmlhttprequest

我想在运行于CORS环境中的Angular 6应用程序中使用cookie进行身份验证。但是,我发送的Cookie会被浏览器忽略,并且不会显示在后续请求中。

由于我处于开发模式,因此Angular CLI服务器 ng serve 为Angular应用程序提供服务。因此,浏览器的网址是

http://localhost:4200/

REST接口在Glassfish 5容器中实现,其URL为:

http://localhost:8080/Tbox_war_exploded/

在Web应用程序中,我为所有响应添加所需的CORS标头:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request,
                       ContainerResponseContext response) throws IOException {
        response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:4200");
        response.getHeaders().add("Access-Control-Allow-Headers",
                                  "origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods",
                                  "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

没有这些头文件,我将无法从Angular应用程序调用REST接口。与他们一起呈现效果很好。当Web应用程序对用户进行身份验证时,它将尝试设置带有返回的标头的cookie,如下所示:

HTTP/1.1 200 OK
Server: GlassFish Server Open Source Edition  5.0 
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  5.0  Java/Oracle Corporation/1.8)
Set-Cookie: tsession=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaXNzIjoiY3l0YWJsZSIsImV4cCI6MTUzMjIzNjA0N30.hhAHcKiZ81M5MZqydOQfHinnLIs3CiNuT45jA_gVMeI;Version=1;Comment="Auth v3";Path=/
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Headers: origin, content-type, accept, authorization
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD
Content-Type: application/json
Content-Length: 928

但是它在这里崩溃了,因为浏览器基本上忽略了 tsession cookie。开发工具不会显示它存储在任何地方,也不会出现在后续请求的标题中。

我发现大多数博客和SO线程都在谈论CORS,但不是Cookie。这里是one thread,涉及CORS + Cookie,但我无法使其正常工作。

所以我被困住了。这里有人发现问题了吗?

更新:

为进一步澄清,以下客户端代码片段是发出所有请求的原因:

const serverURL = 'http://localhost:8080/Tbox_war_exploded/'; 
const headersForJSON: HttpHeaders = new HttpHeaders (
  {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
);

@Injectable()
export class TboxService implements OnInit {

  constructor(private http: HttpClient) {
  }

  httpPostPoReq(path: string, jsonReq: JsonPoReq): Observable<JsonPoReq> {
    return this.http.post<JsonPoReq>(serverURL + path, jsonReq,
       {headers: headersForJSON, withCredentials: true });
  }

我知道设置了 withCredentials 标志,因为设置该标志后,浏览器不再允许将 Access-Control-Allow-Origin:标头值设置为*(通配符)。但是浏览器仍然忽略cookie。 here非常清楚地说明了该标志。

更新#2

我的应用程序可以工作了,我将在不久后发布该问题的答案。希望这对将来遇到同样问题的人有所帮助。

0 个答案:

没有答案