我是Angular2的新手,尝试捕获401错误以进行令牌刷新,并计划重试原始请求…
这是我的authService.refresh方法:
refresh() : Observable<any> { console.log("refreshing token"); this.accessToken = null; let params : string = 'refresh_token=' + this.refreshToken + '&grant_type=refresh_token'; let headers = new Headers(); headers.append('Authorization','Basic ' + this.clientCredentials); headers.append('Content-Type','application/x-www-form-urlencoded'); return Observable.create( observer => { this._http.post('http://localhost:8080/oauth/token',params,{ headers : headers }) .map(res => res.json()).subscribe( (data) => { this.accessToken = data.access_token; observer.next(this.accessToken); observer.complete(); },(error) => { Observable.throw(error); } ); }); }
update(index : number) { let headers = new Headers(); headers.append('Authorization','Bearer ' + this._authService.accessToken); this._http.get('http://localhost:8080/rest/resource',{ headers : headers }) .catch(initialError =>{ if (initialError && initialError.status === 401) { this._authService.refresh().flatMap((data) => { if ( this._authService.accessToken != null) { // retry with new token headers = new Headers(); headers.append('Authorization','Bearer ' + this._authService.accessToken); return this._http.get('http://localhost:8080/rest/resource',{ headers : headers }); } else { return Observable.throw(initialError); } }); } else { return Observable.throw(initialError); } }) .map(res => res.json()) .subscribe( data => { this.resources[index] = data; },error => { console.log("error="+JSON.stringify(error)); } ); }
除了Günter的答案,我还会利用flatMap回调参数中的accessToken而不是使用服务属性:
if (initialError && initialError.status === 401) { this._authService.refresh().flatMap((accessToken) => { // retry with new token headers = new Headers(); headers.append('Authorization','Bearer ' + accessToken); return this._http.get('http://localhost:8080/rest/resource',{ headers : headers }); }); } else { return Observable.throw(initialError); }
本文可能会引起您的兴趣(“处理安全性”部分):