diff --git a/lib/src/main/java/io/ably/lib/rest/Auth.java b/lib/src/main/java/io/ably/lib/rest/Auth.java index 87bb56cac..a5f497970 100644 --- a/lib/src/main/java/io/ably/lib/rest/Auth.java +++ b/lib/src/main/java/io/ably/lib/rest/Auth.java @@ -948,11 +948,9 @@ public TokenDetails assertValidToken() throws AblyException { private TokenDetails assertValidToken(TokenParams params, AuthOptions options, boolean force) throws AblyException { Log.i("Auth.assertValidToken()", ""); if(tokenDetails != null) { - if(tokenDetails.expires == 0 || tokenValid(tokenDetails)) { - if (!force) { - Log.i("Auth.assertValidToken()", "using cached token; expires = " + tokenDetails.expires); - return tokenDetails; - } + if(!force && (tokenDetails.expires == 0 || tokenValid(tokenDetails))) { + Log.i("Auth.assertValidToken()", "using cached token; expires = " + tokenDetails.expires); + return tokenDetails; } else { /* expired, so remove */ Log.i("Auth.assertValidToken()", "deleting expired token"); diff --git a/lib/src/test/java/io/ably/lib/test/rest/RestAuthTest.java b/lib/src/test/java/io/ably/lib/test/rest/RestAuthTest.java index 73b599da4..03337c997 100644 --- a/lib/src/test/java/io/ably/lib/test/rest/RestAuthTest.java +++ b/lib/src/test/java/io/ably/lib/test/rest/RestAuthTest.java @@ -1717,6 +1717,47 @@ public void auth_token_request_json_omitted_defaults() { } } + /** + * Verify that renewing the token when useTokenAuth is true doesn't use the old (expired) token. + */ + @Test + public void auth_renew_token_bearer_auth() { + try { + ClientOptions opts = createOptions(testVars.keys[0].keyStr); + opts.useTokenAuth = true; + opts.defaultTokenParams = new TokenParams() {{ + ttl = 100; + }}; + AblyRest ably = new AblyRest(opts); + + // Any request will issue a new token with the defaultTokenParams and use it. + + ably.channels.get("test").history(null); + TokenDetails oldToken = ably.auth.getTokenDetails(); + + // Sleep until old token expires, then ensure it did. + + Thread.sleep(110); + ClientOptions optsWithOldToken = createOptions(); + optsWithOldToken.tokenDetails = oldToken; + AblyRest ablyWithOldToken = new AblyRest(optsWithOldToken); + try { + ablyWithOldToken.channels.get("test").history(null); + fail("expected old token to be expired already"); + } catch(AblyException e) {} + + // The library should now renew the token using the key. + + ably.channels.get("test").history(null); + TokenDetails newToken = ably.auth.getTokenDetails(); + + assertNotEquals(oldToken.token, newToken.token); + } catch (Exception e) { + e.printStackTrace(); + fail("Unexpected exception"); + } + } + private static TokenServer tokenServer; private static SessionHandlerNanoHTTPD nanoHTTPD;