Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a margin to the automatic JWT refresh #33

Merged
merged 3 commits into from
Mar 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,24 @@ export default Ember.Controller.extend(LoginControllerMixin, {

Please note, the JWT authenticator will decode a token and look for the
expiration time found by looking up the token[Config.tokenExpireName]. It then
calculates the difference between the current time and the token expire time
to determine when to make the next automatic token refresh request.
calculates the difference between the current time and the token expire time —
from which the *refreshLeeway* is subtracted — to determine when to make the
next automatic token refresh request.

For example, your decoded token might look like this:
For example, with the following configuration:

```
ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:token'
};
ENV['simple-auth-token'] = {
refreshAccessTokens: true,
timeFactor: 1,
refreshLeeway: 300 // Refresh the token 5 minutes (300s) before it expires.
};
```

Your decoded token might look like this:

```
token = {
Expand All @@ -100,10 +114,11 @@ token = {
}
```

In this case the token expire name is using the default `exp` as set by the
`Config.tokenExpireName` property.
*In this case the token expire name is using the default `exp` as set by the
`Config.tokenExpireName` property.*

An automatic token refresh request would be sent out at token[Config.tokenExpireName] - now()
If the token issued was valid for an hour, an automatic token refresh request
would be sent out five minutes before the expiration time of the token.

## The Authorizer

Expand Down Expand Up @@ -145,5 +160,6 @@ For the JWT authenticator (in addition to the Token authenticator fields):
refreshAccessTokens: true,
serverTokenRefreshEndpoint: '/api-token-refresh/',
tokenExpireName: 'exp',
refreshLeeway: 0,
timeFactor: 1 // example - set to "1000" to convert incoming seconds to milliseconds.
```
19 changes: 15 additions & 4 deletions addon/authenticators/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ export default TokenAuthenticator.extend({
*/
refreshAccessTokens: true,

/**
The number of seconds to subtract from the token's time of expiration when
scheduling the automatic token refresh call.
@property refreshLeeway
@type Integer
@default 0 (seconds)
*/
refreshLeeway: 0,

/**
The amount of time to wait before refreshing the token - set automatically.
@property refreshTokenTimeout
Expand Down Expand Up @@ -65,6 +74,7 @@ export default TokenAuthenticator.extend({
this.identificationField = Configuration.identificationField;
this.tokenPropertyName = Configuration.tokenPropertyName;
this.refreshAccessTokens = Configuration.refreshAccessTokens;
this.refreshLeeway = Configuration.refreshLeeway;
this.tokenExpireName = Configuration.tokenExpireName;
this.timeFactor = Configuration.timeFactor;
this.headers = Configuration.headers;
Expand Down Expand Up @@ -169,8 +179,9 @@ export default TokenAuthenticator.extend({
Schedules a token refresh request to be sent to the backend after a calculated
`wait` time has passed.

If both `token` and `expiresAt` are non-empty, and `expiresAt` is greater than
the calculated `now`, the token refresh will be scheduled through Ember.run.later.
If both `token` and `expiresAt` are non-empty, and `expiresAt` minus the optional
refres leeway is greater than the calculated `now`, the token refresh will be scheduled
through Ember.run.later.

@method scheduleAccessTokenRefresh
@private
Expand All @@ -180,9 +191,9 @@ export default TokenAuthenticator.extend({
expiresAt = this.resolveTime(expiresAt);

var now = (new Date()).getTime(),
wait = expiresAt - now;
wait = expiresAt - now - (this.refreshLeeway * 1000);

if (!Ember.isEmpty(token) && !Ember.isEmpty(expiresAt) && expiresAt > now) {
if (!Ember.isEmpty(token) && !Ember.isEmpty(expiresAt) && wait > 0) {
Ember.run.cancel(this._refreshTokenTimeout);

delete this._refreshTokenTimeout;
Expand Down
10 changes: 10 additions & 0 deletions addon/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var defaults = {
passwordField: 'password',
tokenPropertyName: 'token',
refreshAccessTokens: true,
refreshLeeway: 0,
tokenExpireName: 'exp',
authorizationPrefix: 'Bearer ',
authorizationHeaderName: 'Authorization',
Expand Down Expand Up @@ -97,6 +98,15 @@ export default {
*/
refreshAccessTokens: defaults.refreshAccessTokens,

/**
The number of seconds to subtract from the token's time of expiration when
scheduling the automatic token refresh call.
@property refreshLeeway
@type Integer
@default 0 (seconds)
*/
refreshLeeway: defaults.refreshLeeway,

/**
The name for which decoded token field represents the token expire time.
@property tokenExpireName
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/authenticators/jwt-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,31 @@ test('#restore does not schedule a token refresh when `expiresAt` < now.', funct
});
});

test('#restore does not schedule a token refresh when `expiresAt` - `refreshLeeway` < now.', function() {
var jwt = JWT.create(),
expiresAt = (new Date()).getTime() + 60000;

var token = {};
token[jwt.identificationField] = '[email protected]';
token[jwt.tokenExpireName] = expiresAt;

token = createFakeToken(token);

var data = {};
data[jwt.tokenPropertyName] = token;
data[jwt.tokenExpireName] = expiresAt;

// Set the refreshLeeway to > expiresAt.
App.authenticator.refreshLeeway = 120;

Ember.run(function() {
App.authenticator.restore(data).then(function() {
// Check that Ember.run.later was not called.
deepEqual(Ember.run.later.getCall(0), null);
});
});
});

test('#authenticate sends an ajax request to the token endpoint', function() {
sinon.spy(Ember.$, 'ajax');

Expand Down
4 changes: 4 additions & 0 deletions tests/unit/configuration-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ test('refreshAccessTokens', function() {
equal(Configuration.refreshAccessTokens, true, 'defaults to true');
});

test('refreshLeeway', function() {
equal(Configuration.refreshLeeway, 0, 'defaults to 0');
});

test('tokenExpireName', function() {
equal(Configuration.tokenExpireName, 'exp', 'defaults to "exp"');
});
Expand Down