Angular 5,httpclient 忽略 post 中设置的 cookie

标签 angular authentication angular5 setcookie

我在 Angular 5 中处理 HttpClient,问题是服务器在登录过程中发送的 cookie,似乎 Angular 忽略了它,因为下一个带有“withCredentials”的请求没有设置它。

我的包.json

.... "@angular/cli": "1.6.3", "@angular/compiler-cli": "^5.0.0", "@angular/language-service": "^5.0.0", ....

我的代码

makeLogin (us:string, password:string): Observable<any> {
    let body : any = new HttpParams()
      .set('username', us)
      .set('password', password);
    return this.http.post(this.urlLogin,
      body.toString(),

      {
        headers: new HttpHeaders()
          .set('Content-Type', 'application/x-www-form-urlencoded')
      }
    );
  }

服务器返回带有这些 header 的 http 200

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:17
Date:Tue, 23 Jan 2018 21:05:46 GMT
Expires:0
Pragma:no-cache
Set-Cookie:JSESSIONID=BF9392ED5DE99710B44845201DD26B3F;path=/;HttpOnly
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

之后,例如下一个请求

getEventt (): Observable<any> {
    return this.http.get('http://localhost:8080/list',{ withCredentials: true });
  }

使用 chrome 或 firefox 开发者工具我看不到发送的 cookie,但如果我使用浏览器或 postman 一切正常,我可以看到发送的 cookie。

我不知道是我做错了什么还是以错误的方式使用了 httpClient。

如果有帮助,服务器部署在 tomcat 8 上,Angular 应用程序运行在 nodejs 上(npm start)

最佳答案

我终于成功了!!

解决方案在 post 请求中,

也许我错了,但 RequestOptions 类似乎在 Angular 5.0.0 中被弃用了,所以在多次尝试正确的配置之后,这是修复的方法

/** POST: add a new hero to the server */
makeLogin (us:string, password:string): Observable<any> {
    let enco : any = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded');

    let body : any = new HttpParams()
    .set('username', us)
    .set('password', password);
    return this.http.post(this.urlServicioLogin,
     body.toString(),
     {
       headers: enco,withCredentials:true
     }
   );
}

现在有了 withCredentials true,我可以在浏览器中看到正在设置的 cookie,然后将其与后续请求一起发送。

注意:如果应用程序必须使用 rest 服务,其中使用 cookie 进行身份验证,则与后端的所有交互都需要将 withCredentials 标志设置为 true。

关于Angular 5,httpclient 忽略 post 中设置的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410884/

相关文章:

AngularFire .subscribe => console.log 在使用 map 或 flatMap 后返回 undefined

google-app-engine - Google App Engine 上的 Radius 服务器?

iphone - 如何设计用于移动应用程序使用的 web api?

authentication - 在客户端 OWIN Web 应用程序中实现 Azure Active Directory 身份验证

webpack - 组件不能作为入口组件

javascript - 如何为 FormGroup 触发 Angular 5 异步验证器 onblur

angular - 使用 rxjs BehaviorSubject 加载微调器

angular - 如何将配置参数传递给 Angular 库?

performance - 销毁 Angular2 应用程序

angular - 如何在 Angular 5 的 header 中添加 CORS 请求