1

Am New to Angualr 2 , am facing problem while refreshing the Token when api response is Non authorized (401 ) error. What want implement this concept by using interceptor . Please suggest any inputs or Suggestions.

M Raju
  • 11
  • 3

3 Answers3

0

In angular 2 we don't have a concept of interceptors, the same can we achieved by creating a custom http service which extends the standard http service. And when in your app module you can direct angular to use your custom http service wherever the http service is required.

Deepak Sharma
  • 1,873
  • 10
  • 23
  • For a detailed answer you can see the following question http://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in-angular2 – Deepak Sharma Sep 20 '16 at 08:33
  • Thanks for replay, below code am using to refresh token this._http.get(url,{ headers: headers }) .map((res: Response) =>{return res.json()}) .catch(error=>{ if(error.status=401&&this.refreshTokenCount<=3) { } }) – M Raju Sep 20 '16 at 08:36
0

Below Code will help to achieve the refresh token Intercepter ` get(url:string) : Observable {

    let headers = new Headers({'Content-Type': 'application/json', 'Authorization': 'bearer ' + this.token});
    return this._http.get(url, {headers: headers})
        .map((res: Response) => {
            return res;
        })
        .catch(error=> {
            if (error.status === 401) {
                return this.RefreshToken().flatMap((newToken) => {
                    let newheaders = new Headers({
                        'Content-Type': 'text/plain',
                        'Authorization': 'bearer ' + this.token
                    });
                    return this._http.request(url, {headers: newheaders});
                })
            } else {
                return Observable.throw(error);
            }
        });
} `
M Raju
  • 11
  • 3
  • I'd like to add one remark. For example if you use JWT, you'd still need a valid token in order to refresh it. As I researched myself on this topic, the best practice would be to refresh the token n minutes/hours before it will have expired. – igsm Oct 01 '17 at 18:06
0

You can better handle the 401 unathorized in subscribe, below is the code, you can use it in the component itself

this.dynamic.getProfileDetails(this.userId, this.password).subscribe(
      v => (this.firstName = v.firstName),
      (err) => {
        // check if it is 401 and the token is invalid
        if (err.status == 401 && err.json().oauth2ErrorCode=='invalid_token') {
          console.log("Error Description " + err.json().oauth2ErrorCode);
          console.log("inside component error");
          //  refresh the token
          console.log("refresh the token")
          this._getNewToken.getNewTokenService().subscribe(
            v => {
              //  token is refreshed so retry the original request
              console.log("retry the original request with the new acces token")
              this.dynamic.getProfileDetails(this.userId, this.password).subscribe(
                v => (this.firstName = v.firstName)
              )
            },
            (refreshErr) => {
              if(refreshErr.status == 401 && refreshErr.json().oauth2ErrorCode=='invalid_token')
              {
                console.log("refresh token 401"+refreshErr.json().oauth2ErrorCode);
                this._router.navigate(['login']);
              }
              else if(refreshErr.status==400)
              {
                console.log("inside 400 "+refreshErr );
                this._router.navigate(['login']);
              }
              else
              {
                console.log("error des "+refreshErr );
                this._router.navigate(['login']);
              }
            }
          );



        }
        else{
               //serve  error logout from the app
                this._router.navigate(['login']);
               console.log("server error");
        }
      }
    );
Ali
  • 97
  • 2
  • 8