如何使用JWT Auth

时间:2019-06-03 17:20:53

标签: angular typescript http

我正在尝试在本地API上发送放置请求。我使用的是JWT拦截器,它可以很好地处理POST,GET和DELETE请求,但不适用于PUT,这是未经授权的。

我在console.log上记录一个GET和PUT请求,它们都显示令牌恰好位于标头上。

PUT请求

{
  "url": "http://localhost:8080/api/tasks/2",
  "body": "",
  "reportProgress": false,
  "withCredentials": false,
  "responseType": "json",
  "method": "PUT",
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": [{
      "name": "Authorization",
      "value": "JWT Token",
      "op": "s"
    }],
    "headers": {},
    "lazyInit": {
      "normalizedNames": {},
      "lazyUpdate": null
    }
  },
  "params": {
    "updates": null,
    "cloneFrom": null,
    "encoder": {},
    "map": {}
  },
  "urlWithParams": "http://localhost:8080/api/tasks/2"
}

GET请求

{
  "url": "http://localhost:8080/api/me",
  "body": null,
  "reportProgress": false,
  "withCredentials": false,
  "responseType": "json",
  "method": "GET",
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": [{
      "name": "Authorization",
      "value": "JWT Token",
      "op": "s"
    }],
    "headers": {},
    "lazyInit": {
      "normalizedNames": {},
      "lazyUpdate": null,
      "headers": {}
    }
  },
  "params": {
    "updates": null,
    "cloneFrom": null,
    "encoder": {},
    "map": {}
  },
  "urlWithParams": "http://localhost:8080/api/me"
}

我的发送看跌期权的服务

  updateSchedule(id): Observable<any>{
    let currentUser = this.authenticationService.currentUservalue;

    const httpOptions = {      
      headers:  new HttpHeaders({
          'Authorization': `${currentUser.token}`
    })
  };
    return this.http.put(`${this._url}/tasks/${id}`, httpOptions)
  }

401错误

PUT http://localhost:8080/api/tasks/2 401 (Unauthorized)

如何在PUT请求上验证此JWT?

1 个答案:

答案 0 :(得分:0)

HttpOptions是第三个参数,第二个必须是body。如果没有主体,请放置一个空字符串。在这里https://angular.io/guide/http#making-a-put-request

return this.http.put(`${this._url}/tasks/${id}`,'', httpOptions)