I'm new to Angular2 and trying catch 401 error for token refresh with the plan to retry original request...
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));
}
);
}
This doesn't work for some reason...
I wonder what is the correct implementation of token refresh functionality in angular2?enter code here
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"):
There is no need to use Observable.create(
return this._http.post('http://localhost:8080/oauth/token', params, {
headers : headers
})
.map(res => res.json())
.map(data => {
this.accessToken = data.access_token;
observer.next(this.accessToken);
observer.complete();
},
).catch(error) => Observable.throw(error));
just don't call .subscribe()
(which will return a Subscription
instead of an Observable
, instead use .map(...)
and .catch(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With