在使用withCredentials的设备上未发送Ionic 3中的Cookie:true
问题描述:
我正尝试使用Ionic 3/Angular 4.3为现有Web应用程序构建移动客户端。在使用withCredentials的设备上未发送Ionic 3中的Cookie:true
我们使用cookie进行会话和CSRF保护。
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需要地址标志)运行:我已经为了安装和使用HTTP请求发送令牌饼干实行以下HttpInterceptor
。
但是,当使用ionic cordova run android
从Android设备进行测试时,Cookie似乎不会被发送或持续存在。
从上面可以看到,我已将withCredentials
设置为true
,因为大多数类似帖子的回复建议。
答
Cookie不是处理移动设备上身份验证的好方法。有多个cookie存储(webview有一个,有一个本地的,我认为即使一些HTTP模块有一个),所以他们必须同步工作可靠。 Android有自己的CookieSyncManager作为一个实用程序(新的webviews显然可以自己)。另外,当您的设备处于低内存时,Cookie将排在前面,以便被操作系统清除。因此,您的cookies会不时丢失,您的用户会因为需要重新登录而感到不安。
那你应该怎么做呢?你应该实现一个基于令牌的认证系统。使用native-storage或某些sql-lite存储来存储令牌。
服务器端组件是否处理自定义请求标头要求正确的请求前请求? – CBroe
@CBroe我已经允许在开发服务器上的所有来源,但不是在生产服务器上(我一直在阅读,这是没有必要的,因为设备访问与原始文件''') – Jaysbays
谈论https:// * .com/a/13997235/1427878 – CBroe