vmanchev / ionic3-seed-jwt

Ionic 3 seed project with JWT support. It works together with the backend from here https://github.com/vmanchev/laravel-jwt
83 stars 40 forks source link

Refresh token Function ! #2

Open jehadja opened 7 years ago

jehadja commented 7 years ago

Hi, Thank you for this Great efforts ! and i am sorry for my english language its not my native . but i have a question about Refresh token function in you Laravel project you refresh token each 1 hour 'ttl' => 60, and also in API you put refresh Route

    $api->get('refresh', [
        'middleware' => 'jwt.refresh',
        function() {
          return response()->json([
                      'message' => 'By accessing this endpoint, you can refresh your access token at each request. Check out this response headers!'
          ]);
        }
    ]);

i didn't see any action for this on ionic side i mean after 1 hour the token will be changed and black listed do you have any idea how to refresh it ? i tried the following code after login complete i run this function

  public scheduleRefresh() {
    // If the user is authenticated, use the token stream
    // provided by angular2-jwt and flatMap the token

    let source = Observable.of(this.idToken).flatMap(
      token => {
        // The delay to generate in this case is the difference
        // between the expiry time and the issued at time
        let jwtIat = this.jwtHelper.decodeToken(token).iat;
        let jwtExp = this.jwtHelper.decodeToken(token).exp;
        let iat = new Date(0);
        let exp = new Date(0);

        let delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat));
        console.log("will start refresh after :",(delay/1000)/60);
        if(delay-1000<=0)
        delay = 1;
        return Observable.interval(delay);
      });

    this.refreshSubscription = source.subscribe(() => {
      this.getNewJwt();
    });
  }

and more over when application run


    public startupTokenRefresh() {
      // If the user is authenticated, use the token stream
      // provided by angular2-jwt and flatMap the token

      this.storage.get("API_TOKEN_VAL").then((thetoken)=>{

        if(thetoken){

          let source = Observable.of(thetoken).flatMap(
            token => {
              // Get the expiry time to generate
              // a delay in milliseconds
              let now: number = new Date().valueOf();
              let jwtExp: number = this.jwtHelper.decodeToken(token).exp;
              let exp: Date = new Date(0);
              exp.setUTCSeconds(jwtExp);
              let delay: number = exp.valueOf() - now;

              if(delay <= 0) {
                delay=1;
              }
              console.info("thedlyais:",delay);
              // Use the delay in a timer to
              // run the refresh at the proper time
              return Observable.timer(delay);
            });

           // Once the delay time from above is
           // reached, get a new JWT and schedule
           // additional refreshes
           source.subscribe(() => {
             this.getNewJwt();
             this.scheduleRefresh();
           });

        }else{
          //there is no user logined
          console.info("there is no user logined ");

        }

      });

      }

it some time work some time not my question if it needed on your project or not ? shall i send pull request ?

or you have another way to run the schedule Refresh

the getNewJwt function is following

public getNewJwt() {

    console.log("update token");
     let seq = this.authHttp.post('https://beckendomian.com/RefreshToken', '').share();
      seq
       .map(res => res.json())
       .subscribe(res => {
         console.log(JSON.stringify(res));
         // If the API returned a successful response, mark the user as logged in
         if(res.status == 'success') {
             this.storage.set("API_TOKEN_VAL", res.token).then(()=>{

             });
          } else {
            console.log("erorr");
          }
       }, err => {
         console.error('ERROR', err);

       });

 }

-- update after one hour passed have this issue profile work normally as its stored on storage book page give the following error from backend

image as it need to be refreshed !

best !

jehadja commented 7 years ago

Done i send PR for refreshing the JWT you need just to approve PR , also you can turn off APP completey and come before 'refresh_ttl' => 20160, finish which is time per minute for token to be valid to refresh again you can make it 30 days for normal APP 👍

with regards

image

vmanchev commented 7 years ago

Thank you very much for your help! It is really appreciated. Could you please update the PHP file as per my comment, probably just the code was pasted twice.