How to handle auth0 403 error without adding specific code everywhere (Retrofit/okhttp/RxAndroid)

后端 未结 2 1602
野趣味
野趣味 2021-01-02 02:05

I am using Auth0, which gives me a JWT (json web token) and a refreshtoken. I use this JWT in the http headers to communicate with my backend.

It could happen, that

2条回答
  •  轮回少年
    2021-01-02 02:59

    Instead of refreshing tokens only after receiving a 403 response, you could check the expiration time locally and refresh accordingly by checking the token's exp claim. For example, this example uses the same approach in Angular. It's not specific to Android, but the idea is the same:

    jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
      var idToken = store.get('token');
      var refreshToken = store.get('refreshToken');
      if (!idToken || !refreshToken) {
        return null;
      }
      // If token has expired, refresh it and return the new token
      if (jwtHelper.isTokenExpired(idToken)) {
        return auth.refreshIdToken(refreshToken).then(function(idToken) {
          store.set('token', idToken);
          return idToken;
        });
      // If not expired, return the token directly
      } else {
        return idToken;
      }
    }
    

提交回复
热议问题