# How do you handle token refreshing?

**URL:** <https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169>\
**Category:** ionic-v3\
**Created:** [May 29, 2017, 4:05pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169 "2017-05-29T16:05:51Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 29, 2017, 4:05pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/1 "2017-05-29T16:05:51Z")

</div>

I’m using JWTs for authentication. The token is valid for 1 hour. The app will be a browser based app & ios app. I have around 4 pages (Login, Category search, Product search, confirmation/add to order). Every single one of these pages makes HTTP requests to my back end so I have to have a valid token for each one.

I can think of two solutions

1. On login, schedule a refresh every 59 minutes. But will this work well for a browser app? Say for example a user leaves their browser open and comes back after 2 hours and starts searching for a product but the token is now expired so the backend is returning an error

2. Make a `refreshToken()` function that is called before every HTTP request like

But what if the token expires in the middle of the user searching?

Thoughts? How do you handle token refreshing in your apps?

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 29, 2017, 7:11pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/2 "2017-05-29T19:11:19Z")

</div>

You can improve method 2 by isolating it into a token provider. When the token provider is asked for a token, it can look at the `exp` claim of the one it has, and retrieve a new one only if needed.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 30, 2017, 12:28am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/3 "2017-05-30T00:28:10Z")

</div>

Yeah thats a good idea. What im not sure about is if it will break my app if the token expires in the middle of the searches (example: user begins searching and 10 secs later the token expires while the user is still typing).

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 30, 2017, 2:14am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/4 "2017-05-30T02:14:49Z")

</div>

Should not be a problem. The token provider service is responsible for ensuring that you always have a valid token, and the authenticated http service will only make requests with valid tokens.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 30, 2017, 2:50am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/5 "2017-05-30T02:50:04Z")

</div>

So in the token provider I can just use something like angular2-jwt’s `tokenNotExpired()` function that returns true or false depending on if the token is in storage and hasnt expired yet… Will it really be this simple?

```
 get token
 check if its expired
    return true or false
```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 30, 2017, 3:05am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/6 "2017-05-30T03:05:27Z")

</div>

Not quite, because you’ll have to return some future (Promise or Observable) in order to handle the situation where the token was expired and needs to be refreshed.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 30, 2017, 3:25am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/7 "2017-05-30T03:25:30Z")

</div>

Oh right of course. This is what I came up with real quickly, would it work? Or is there a better way to do it?

```
 get token
 if token expired
    refreshToken();

refreshToken() {
    return this.http.get("")
    .map((response: Response) => {
        var token: any = response.json();
          storage.set('token', token);
     }
```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 30, 2017, 4:35am UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/8 "2017-05-30T04:35:18Z")

</div>

More or less, but `map` should not modify state, so I would write it more like this:

```auto
getToken(): Observable<string> {
  let rv: Observable<string>;
  if (!this.isTokenValid()) {
    rv = this.http.get(url).map(rsp => rsp.json());
    rv.subscribe(token => {
      this.token = token;
      this.storage.set('token', token)
    });
  } else {
    rv = Observable.of(this.token);
  }
  return rv;
}

```

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 30, 2017, 6:03pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/9 "2017-05-30T18:03:23Z")

</div>

Thanks I’m going to give this a try right now. What does this line do? `rv = Observable.of(this.token);`

The documentation says that `of` Converts arguments to an observable sequence. So you can subscribe to it and stuff? But would there be any point to that?

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 30, 2017, 6:55pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/10 "2017-05-30T18:55:46Z")

</div>

> [@nb1990](#):
>
> would there be any point to that?

It makes the return value consistently an Observable, so that the outside world (callers of this function) need not know or care whether the token was cached or needed to be fetched anew.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [May 31, 2017, 9:57pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/11 "2017-05-31T21:57:28Z")

</div>

Thanks for your help @rapropos here is what sort of works for my app in case anybody else needs help in the future.

```
 get(): Promise<any> {
    return this.storage.get('token_id').then(token_id => {
      this.token_id = token_id;
    });
  }

  set(token_id) {
    this.storage.set('token_id', token_id);
  }

  refresh(): Observable <any> {

    let obs = Observable.fromPromise(this.gettoken_id())
      .filter(() => this.jwtHelper.istoken_idExpired(this.token_id))
      .flatMap(() => this.authHttp.get(''));
    obs.subscribe((response: Response) => {
      this.token_id = response.json().token_id;
      this.settoken_id(this.token_id);
    }, (error: Response) => {
      console.log(error);
    });
    return obs;
  }

```

I just call refresh() before my http calls. However there is one which I am still trying to figure out. Say a user is typing “Hel” in the search bar and the token expires but then they type “l” a call is sent to my API without a token but if they type “o” it sends a call to my API with the token so the token is not getting stored before the call is made. I will post here if I find a solution or why its happening

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 31, 2017, 10:16pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/12 "2017-05-31T22:16:46Z")

</div>

Please use `string` instead of `any`.

There is one very subtle bug in `get()`. If you are intending for somebody to be able to do:

```auto
this.tokenService.get().then((jwt) => {
  // woot I got a JWT
});

```

…it won’t work. The `then` clause in `get()` swallows the token. You either need to explicitly do this:

```auto
get(): Promise<string> {
  return this.storage.get('token_id').then((token) => {
    this.token_id = token;
    return token;
  });
}

```

or you need to write it like this:

```auto
get(): Promise<string> {
  return this.storage.get('token_id').then(token => this.token_id = token);
}

```

This special form (with no `{}` around the code block) implicitly returns the expression on the right hand of the `=>`.

All of this is mooted by the fact that `get()` shouldn’t hit storage every time it is called. A better strategy is to do it once in the constructor:

```auto
token: string;
constructor(private _storage: Storage) {
  _storage.ready().then(() => _storage.get('token_id'))
    .then(token => this.token = token);
}

get(): Observable<string> {
  if (!this.jwtHelper.isValid(this.token)) {
    return this.authHttp.get('').map((rsp) => {
      this.token = rsp.json().token_id;
      this._storage.ready().then(() => this._storage.set('token_id', this.token));
      return this.token;
    });
  } else {
    return Observable.of(this.token);
  }
}

```

I don’t see a need for `set()`, because presumably the only source of valid tokens comes from calls to `get()` when there wasn’t one at the time. `jwtHelper.isTokenValid()` needs to be able to handle the situation where it is passed something `null` or `undefined`, and consider that invalid. That solves your initialization case, at the relatively small cost that you will hit the backend (perhaps needlessly) if `get()` is called before the initial storage read resolves. If that is a concern to you, you could guard against it by waiting on the initial read in `get()`.

```auto

```

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [June 2, 2017, 8:49pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/14 "2017-06-02T20:49:15Z")

</div>

I finally got a chance to try and implement this and I’m still having the same problem. I tried all the ways you listed! Also the last `get()` method doesn’t work for me it never even calls the API I have to do it this way

```
refresh(): Observable <any> {

    let obs = Observable.fromPromise(this.getToken())
      .filter(() => this.jwtHelper.istokenexpired(this.token_id))
      .flatMap(() => this.authHttp.get(''));
    obs.subscribe((response: Response) => {
      this.token_id = response.json().token_id;
      this.settoken(this.token_id);
    }, (error: Response) => {
      console.log(error);
    });
    return obs;
  }

```

If I do it the way you suggest I get a “token not provided” error

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [June 2, 2017, 8:56pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/15 "2017-06-02T20:56:09Z")

</div>

> [@nb1990](#):
>
> the last get() method doesn’t work for me it never even calls the API

I can’t see how that could be.

There are three possible states for `this.token` at the time `get()` is called:

- falsy: `null` or `undefined`
- truthy yet invalid
- truthy and valid

In either of the first two cases, `jwtHelper` should tell us the token is invalid, and we will follow the `if` path which calls `authHttp.get()` (presumably what you mean by “calls the API”). In the third case, we follow the `else` path with no need to hit the API because our token is valid.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [June 2, 2017, 9:25pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/16 "2017-06-02T21:25:55Z")

</div>

o I logged my token on login and also in the get(): method as the first line and they are different. I also logged the token in the constructor after storage.get() and it says undefined

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [June 2, 2017, 9:32pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/17 "2017-06-02T21:32:08Z")

</div>

Can you post the `jwtHelper` class? I want to make certain that it handles falsy values correctly.

> [@nb1990](#):
>
> I also logged the token in the constructor after storage.get() and it says undefined

If by this, you mean something like this:

```auto
constructor(storage: Storage) {
  storage.ready().then(() => storage.get('token_id'))
    .then(token => this.token = token);
  console.log(this.token);
}

```

That’s the nature of the beast. The only place you can put the log and have it have any meaning is inside the `then` clause right after you have assigned to `this.token`. Not outside.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [June 2, 2017, 9:39pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/18 "2017-06-02T21:39:00Z")

</div>

I see. Thats how I was logging it so I guess thats why.

```
public isTokenExpired(token: string, offsetSeconds?: number): boolean {
    let date = this.getTokenExpirationDate(token);
    offsetSeconds = offsetSeconds || 0;

    if (date == null) {
      return false;
    }

    // Token expired?
    return !(date.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
  }
  }

```

[Here](https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts) is the full Angular-JWT package source code

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [June 2, 2017, 9:43pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/19 "2017-06-02T21:43:25Z")

</div>

I don’t know how more clearly I could have stated this:

> [@rapropos](#):
>
> jwtHelper.isTokenValid() needs to be able to handle the situation where it is passed something null or undefined, and consider that invalid.

It doesn’t, which is causing your problem. You need to do something like this:

```auto
isTokenValid(): boolean {
  return this.token && !this.jwtHelper.isTokenExpired(this.token);
}

```

…or any other solution you find more readable, but **it has to consider falsy tokens invalid**.

---

<div class="post-metadata">

**Author:** ![nb1990](https://avatars.discourse-cdn.com/v4/letter/n/df788c/32.png) [@nb1990](https://forum.ionicframework.com/u/nb1990)\
**Post date:** [June 2, 2017, 9:57pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/20 "2017-06-02T21:57:41Z")

</div>

its still not working because `this.token` is storing the token from the last session even when I reload. I guess I have to clear the storage but still if a new token is set on login shouldnt it clear the old one and the constructor in my token provider get the new one from storage?

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [June 2, 2017, 10:02pm UTC](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169/21 "2017-06-02T22:02:50Z")

</div>

I really wish you would bother to read the things I write and explain where my assumptions aren’t valid. Again,

> [@rapropos](#):
>
> I don’t see a need for set(), **because presumably the only source of valid tokens comes from calls to get() when there wasn’t one at the time.**

Now you are telling me that “a new token is set on login”, so the tokens _aren’t_ just coming from the `authHttp.get()` call inside `get()`. If new tokens are coming in from somewhere else, you need to update both storage and the stored `token` property of the `TokenProvider`.

[Next page](https://forum.ionicframework.com/t/how-do-you-handle-token-refreshing/92169.md?page=2)
