【发布时间】:2018-04-01 00:08:54
【问题描述】:
我正在尝试使用 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,正如大多数类似帖子的答案所暗示的那样。
【问题讨论】:
-
服务器端组件处理自定义请求标头所需的飞行前请求是否正确?
-
@CBroe 我已允许开发服务器上的所有来源,但不允许生产服务器上的所有来源(我一直在阅读,这是没有必要的,因为设备使用来源
file进行访问) -
@CBroe 是的,我已经相应地设置了允许的来源、标头、凭据和公开的标头。
-
那我建议你把安卓设备挂到电脑上,这样你就可以通过Chrome开发工具或者类似的工具做一些远程调试,这样你就可以检查错误,cookie是否首先收到,等等。
标签: angular cordova cookies ionic-framework ionic2