Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Catching 401 error for token refresh

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

like image 427
Alex Avatar asked Apr 28 '16 04:04

Alex


2 Answers

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"):

  • http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/
like image 169
Thierry Templier Avatar answered Oct 21 '22 22:10

Thierry Templier


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(...)

like image 2
Günter Zöchbauer Avatar answered Oct 21 '22 21:10

Günter Zöchbauer