问题描述
我是Angular2的新手,并尝试捕获401错误以进行令牌刷新,并计划重试原始请求...
I'm new to Angular2 and trying catch 401 error for token refresh with the plan to retry original request...
这是我的authService.refresh方法:
Here is my authService.refresh method:
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);
}
);
});
}
然后我尝试在组件方法中使用刷新功能:
and then I try to use refresh functionality in my component method:
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));
}
);
}
由于某些原因,此方法不起作用...我想知道在angular2中令牌刷新功能的正确实现是什么?enter code here
This doesn't work for some reason...I wonder what is the correct implementation of token refresh functionality in angular2?enter code here
推荐答案
除了Günter的回答,我将利用flatMap
回调参数中的accessToken
而不是使用service属性:
In addition to the Günter's answer, I would leverage the accessToken
from the flatMap
callback parameter instead of using a service property:
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);
}
本文可能会让您感兴趣(处理安全性"部分):
This article could interest you (section "Handling security"):
这篇关于Angular2:捕获401错误以刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!