如何将授权令牌添加到HTTP请求

时间:2019-05-14 14:38:34

标签: angular typescript rest spring-boot

达到我的休息终点时,我收到401未经授权的错误,这是因为我增加了安全性,我不确定我是否正确执行了http标头部分。

该应用程序利用了Spring Boot后端Rest API,我知道它可以工作,因为当我通过邮递员获得令牌并再次在邮递员中使用该授权令牌访问该API时,它就可以正常工作。

getWeatherByCityAndCountry(city: string, country: string): Promise<Weather> {

    let headers = new HttpHeaders();
    headers = headers.append('Authorization', 'Bearer '+ this.accessToken);
    return this.http.get(this.baseUrl + '/byCity/' + city + '/' + country, {headers: headers})
      .toPromise()
      .then(response => response as Weather)
      .catch(this.handleError)
  }

accessToken已使用邮递员的令牌值进行了硬编码。

1 个答案:

答案 0 :(得分:2)

我建议添加一个拦截器,以捕获所有请求,这样您就不必在每次请求时都手动添加它们。

import {
  Observable
} from 'rxjs';
import {
  Injectable
} from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from '@angular/common/http';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
    const responseType = req.responseType || 'json';
    const apiToken = localStorage.getItem('Authorization');
    const authed = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + apiToken),
      responseType
    });
    const notAuthed = req.clone({
      responseType
    });
    const authReq = apiToken ? authed : notAuthed;

    return next.handle(authReq);
  }
}

将以下内容添加到模块提供程序阵列中。

{
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true
}