how to refresh the access token using custom http in angular 2?

后端 未结 3 771
孤独总比滥情好
孤独总比滥情好 2021-02-06 18:50

I am using token based authentication in my application. My backend is developed using restful service(spring).The backend code is very well generating the required the access t

3条回答
  •  遥遥无期
    2021-02-06 19:44

    thanks for replying @dragonfly, this worked for me

        post(url: string, body: any, options?: RequestOptionsArgs): Observable {
            //check if the token is expired then set the latest token
                    if (this.isTokenExpired) {
                        options.headers.set('Authorization', 'Bearer ' + localStorage.getItem("accessToken"));
       }
    
      return super.post(url, body, options)
             .catch((err) => {
      //if authentication error
          if (err.status === 401) {
           this.isTokenExpired = true;
          options.headers.set('Authorization', 'Bearer ' + localStorage.getItem("accessToken"));
        //refresh the token
     let refreshUrl = this.refreshTokenUrl;
        //pass the refresh token 
     refreshUrl = refreshUrl.replace(':refreshToken', localStorage.getItem("refreshToken"));
     //rest the access token
      return super.get(refreshUrl).mergeMap((tokenObj) => {
      localStorage.setItem("accessToken", tokenObj.json().value);
       // reset the headers
        options.headers.set('Authorization', 'Bearer ' + localStorage.getItem("accessToken"));
    //retry the request with the new access token
    return this.post(url, body, options)
     })
      .catch((refreshErr) => {
        if (refreshErr.status == 400) {
               console.log("refesh err");
        window.location.href = 'request=logout';
       }
     return Observable.throw(refreshErr);
      })
      } else {
      return err;
      }
     })
    }
    

    Can you tell how are you updating the token(this.authenticationService.updateToken())?

提交回复
热议问题