Ionic 3中的Cookie未使用withCredentials在设备上发送:true

时间:2017-10-19 20:45:15

标签: angular cordova cookies ionic-framework ionic2

我正在尝试使用Ionic 3 / Angular 4.3为现有的Web应用程序构建移动客户端。

我们正在使用Cookie进行会话和CSRF保护。我已实现以下HttpInterceptor以附加和发送带有HTTP请求的令牌cookie:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from "rxjs";
import { CookieService } from 'ngx-cookie';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private cookies: CookieService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    var authReq = this.cookies.get('XSRF-TOKEN') ? request.clone({
      withCredentials: true,
      headers: request.headers.set('X-XSRF-TOKEN', this.cookies.get('XSRF-TOKEN'))
    }) : request.clone({ withCredentials: true });
    return next.handle(authReq);
  }
}

只要我使用ionic serve address=localhost(绕过CORS需要地址标志)运行,浏览器的测试就可以正常工作。

但是,使用ionic cordova run android从Android设备进行测试时,似乎无法发送或保留Cookie。

正如您从上面所看到的,我已将withCredentials设置为true,因为大多数类似帖子的答案都表明了这一点。

1 个答案:

答案 0 :(得分:0)

Cookie不是处理移动设备身份验证的好方法。有多个cookie存储(webview有一个,有一个本地的,我认为甚至一些HTTP模块有一个)所以他们必须同步才能工作可靠。 Android有自己的CookieSyncManager作为实用程序(较新的webview可以自己显示)。此外,当您的设备处于低内存时,Cookie位于前排,以便被操作系统清除。因此,您的Cookie会不时丢失,您的用户会因为必须重新登录而感到不安。

那你该怎么做呢?您应该实现基于令牌的身份验证系统。使用native-storage或某些sql-lite存储来存储令牌。