I have an ionic 2 mobile application that uses Json Web Tokens(JWT) to authenticate to various routes on a node.js API. These JWTs have a short expire time, and need to be refreshed using a refresh token. The refresh token is just a random string that is stored both in the database and on the mobile device. Please note: I am NOT using OAuth.
How can I refactor my API calls so that they all go through one method which will send a refresh token if the initial API call gets a 401 Unauthorized response due to an expired JWT? Otherwise, I will need to write the logic for handling that response in every single API call which I would like to avoid.
Here is an example of one method I have implemented in typescript that calls the API. It is not currently handling a 401 Unauthorized response nor is it sending the refresh token yet:
public setBeerPref(beerPrefs) {
return new Promise((resolve, reject) => {
this.storage.get('email').then((email) => {
this.storage.get('token').then((token) => {
beerPrefs["email"] = email;
let headers = new Headers();
headers.append('Authorization', token);
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post('apiURL', beerPrefs, options)
.subscribe(res => {
let data = res.json();
resolve(data);
resolve(res.json());
}, (err) => {
reject(err);
});
});
});
});
}