如何通过AngularJS传递JsonWebToken(JWT)

时间:2018-11-20 23:32:14

标签: angularjs django-rest-framework jwt

我创建了一个以JWT作为身份验证方法的Django RESTful API,但无法使用angularJS将令牌作为标头传递。

我认为我的API上没有错误,因为我使用了此脚本获取的令牌并在Postman中对其进行了测试: enter image description here

我的JWT令牌身份验证脚本在这里:

 // Uses http.get() to load data from a single API endpoint
  list() {
    return this.http.get('api/', this.getHttpOptions());
  }

// helper function to build the HTTP headers
  getHttpOptions() {
    return {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'JWT ' + this._userService.token
      })
    };
  }

我在这里尝试使用http.get()。预先感谢!

错误将类似于:

401 (Unauthorized)

3 个答案:

答案 0 :(得分:1)

尝试一下:

list() {
return this.http.get('api/', { this.getHttpOptions() });  
}

getHttpOptions() {
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'JWT ' + this._userService.token
  }); 
   return headers;
}

答案 1 :(得分:0)

JWT for CakePHP3在JWT上存在相同问题,请按照标题进行修改,也许会有所帮助。

this.http.get('api/', { headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'JWT ' + this._userService.token,
    'Authenticationtoken': 'JWT ' + this._userService.token
}) });

答案 2 :(得分:0)

谢谢大家, 我发现问题与CORS有关,我的解决方案在这里,有两种方法可以解决此问题,一种是在您的http请求中添加“ Access-Control-Allow-Origin”:“ *”,有时您需要添加更多。另一个答案是在后端添加CORS_ORIGIN_WHITELIST ='localhost:4200'。 https://www.youtube.com/watch?v=OIbndrrUYiY