角度服务中的Auth0承载令牌

时间:2019-03-20 13:01:59

标签: angular

我有一个角度服务,可触发对后端系统的不同休息请求。我想将基于auth0的身份验证添加到http头,该头在定义类之前已定义为常量。

服务

const ZUORA_URL = 'https://jangoepelapitest.azure-api.net/gocsso';
const headers = new HttpHeaders({
  'Access-Control-Allow-Origin': '*',
  'Authorization': 'Bearer ***TOKEN***',
  'Content-Type': 'application/json'
});

@Injectable({
  providedIn: 'root'
})
export class ZuoraService {
  constructor(private http: HttpClient) {}

  // INVOICES
  getInvoice(id: String): Observable<any> {
    return this.http.get(ZUORA_URL + '/v1/invoices/' + id + '/files', {
      headers
    });
  }

  reverseInvoice(id: String): Observable<any> {
    console.log('Invoice reversed');
    return this.http.put(ZUORA_URL + '/v1/invoices/' + id + '/reverse', {
      'applyEffectiveDate': '2017-02-20',
      'memoDate': '2017-02-20'
    }, {
      headers
    });
  }
...
}

auth0令牌生成对于测试工作正常,我向中央应用程序组件添加了以下代码:

APP组件

  constructor(public auth: AuthService) {
    auth.handleAuthentication();
  }
  ngOnInit() {
    console.log('AppComponent: OnInit()');
    if (localStorage.getItem('isLoggedIn') === 'true') {
      this.auth.renewTokens();
    }
  }

当我将生成的令牌添加到标题(复制/粘贴)时,授权工作正常。如何将生成的令牌添加到服务的标头结构中?

欢呼 马尔特

2 个答案:

答案 0 :(得分:2)

为HTTP拦截器创建服务:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public auth: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headers = new HttpHeaders({
    'Access-Control-Allow-Origin': '*',
    'Authorization': 'Bearer ***TOKEN***',
    'Content-Type': 'application/json'
    });

    request = request.clone({
      setHeaders: {
        headers
      }
    });

    return next.handle(request);
  }
}

从OAuth服务获取令牌,并将其设置在上述类的标题授权中。

并在app.module.ts中向您的提供程序添加拦截器:

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

这随每个HTTP请求一起发送令牌。

答案 1 :(得分:0)

您可以使用HttpInterceptor,它将在发送请求之前拦截请求,并且您可以为Bearer令牌设置标头:https://angular.io/api/common/http/HttpInterceptor

您可以从服务或直接从Cookie或本地存储中获取令牌。

相关问题