我已经使用刷新令牌(刷新令牌然后重试http请求)成功开发了一个angular2拦截器,其中access_token和refresh_token都存储在localStorage中。
以下是在我的“AuthService”中刷新令牌的代码:
refreshToken():Observable<Response>
{
let refToken: string = localStorage.getItem("bdRefreshToken");
let username: string = localStorage.getItem("bdUsername");
let body = "grant_type=refresh_token"
+"&client_id=" + Settings.loginInfo.client_id
+"&client_secret=" + Settings.loginInfo.client_secret
+"&scope=" + Settings.loginInfo.scope
+"&username="+username
+"&refresh_token="+refToken;
let header = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let ro:RequestOptions = new RequestOptions({
headers: header
});
return this._http.post(Settings.tokenEndpoint, body, ro)
//.map(res => res.json())
.map(data => {
let d = data.json();
localStorage.setItem('bdAccessToken', d.access_token);
localStorage.setItem('bdRefreshToken', d.refresh_token);
this.saveRoles(d.access_token);
return data;
}
)
.catch(error => {
this.logout();
return Observable.throw(error)
});
}
以下是我继承的http类的一部分,它充当拦截器:
get(url:string, options?:RequestOptions):Observable<Response>
{
return super.get(url, this.getAuthorizedOptions())
.catch(err => {
if (err && err.status === 401){
return this._authService.refreshToken()
.flatMap(r =>
super.get(url, this.getAuthorizedOptions())
)
.catch(err2 => {
this.redirect();
return Observable.throw(err2);
});
}
else {
return Observable.throw(err);
}
});
}
private getAuthorizedOptions():RequestOptions
{
let token = localStorage.get('bdAccessToken');
let header = new Headers({
'Authorization': 'Bearer '+ token
});
let ro = new RequestOptions({
headers: header
});
let options = new RequestOptions();
if (options.headers) options.headers.delete("Authorization");
options.headers = header;
return options;
}
现在,我一直在尝试在Ionic中开发相同的东西,但是,由于Ionic Storage的异步特性,我无法使其工作。从存储中检索值并不像localStorage.get(item)
那么简单,您必须执行以下操作:storage.get(item).then(v => do stuff...)
。
我希望创建一个AuthService和一个继承的Http类作为拦截器;它采用以下标准程序: