Angular 2头部身份验证令牌丢失

时间:2018-06-11 12:23:58

标签: javascript angular express header jwt

我遇到了一个恼人的错误。 我在http标头中发送auth令牌,但是当明确处理请求时,则失去了身份验证令牌。

这是我的代码:

表达身份验证:

app.all(process.env.API_BASE + "*", (req: any, res: any, next: any) => {

    if (req.path.includes(process.env.API_BASE + "login")) return next();
    if (req.path.includes(process.env.API_BASE + "signup")) return next();

    console.log(req.headers);

    return auth.authenticate((err: any, user: any, info: any) => {
        if (err) { return next(err); }
        if (!user) {
            if (info.name === "TokenExpiredError") {
                return res.status(401).json({ message: "Your token has expired. Please generate a new one" });
            } else {
                return res.status(401).json({ message: info.message });
            }
        }
        app.set("user", user);
        return next();
    })(req, res, next);
});

angular2(v6)GET请求:

      public get<T>(path: string, param: string | number = '', queryParams: Object = {}, etag?: string): Promise<T> {
    const requestOptions = this.generateOptions();
    const builtUrl = this.buildUrl(path, param, queryParams);
    return this.http.get<T>(builtUrl, requestOptions)
    .toPromise()
    .catch(this.handleGlobalError);
  }

  private generateOptions() {
    let headers = new HttpHeaders()
    .set('Content-Type', 'application/json')
    .set('Access-Control-Allow-Origin', '*')

   if (this._token) {
    headers = Object.assign(headers, headers.set('Authorization', 
    this._token));
  }

  if (etag) {
   headers = Object.assign(headers, headers.set('If-None-Match', etag));
  }

  const options = {
   headers: headers,
  };

  return options;
 }

我还在PostMan中检查了它的标题如下: enter image description here

服务器记录了传入的请求,第一个请求来自POSTMAN的图片,第二个来自我的角应用程序:

enter image description here

根据NUNICORN ANSWER编辑:

private generateOptions(etag?: string) {
let withCred = false;
let headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Access-Control-Allow-Origin', '*')

if (this._token) {
  withCred = true;
  headers.set('Authorization', this._token);
  //headers = Object.assign(headers, headers.set('Authorization', this._token));
}

const options = {
  headers: headers,
  withCredentials: withCred
};

return options;
}

不幸的是它仍然破碎。

2 个答案:

答案 0 :(得分:0)

请替换

部分
DataMember

 if (this._token) {
         headers = Object.assign(headers, headers.set('Authorization', 
         this._token));
 }

答案 1 :(得分:0)

HttpClient发送请求时,您需要将withCredentials覆盖设置为true,否则您的授权标头将被删除。

POST次请求通常更为明显,但也适用于GET次请求。

有关http覆盖的更多信息,请参阅:https://angular.io/api/common/http/HttpClient#get