Skip to content

Commit

Permalink
Merge pull request #354 from ably/350-renew-token
Browse files Browse the repository at this point in the history
Auth.assertValidToken: always remove old token when force == true.
  • Loading branch information
tcard authored Sep 29, 2017
2 parents 73cb76d + 8a5cccb commit 3ec0d8a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
8 changes: 3 additions & 5 deletions lib/src/main/java/io/ably/lib/rest/Auth.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
41 changes: 41 additions & 0 deletions lib/src/test/java/io/ably/lib/test/rest/RestAuthTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down

0 comments on commit 3ec0d8a

Please sign in to comment.