Skip to content

Commit 4fc74a4

Browse files
committed
Refresh access tokens before expiry
We've seen a small number of exceptions in Experience CS[1] which are caused by a 401 response from Editor API. I'm fairly confident these are occurring when the access token used to make the request to Editor API has expired. My hypothesis is that the token is valid at the time the request comes into Experience CS (and therefore the auto refresh behaviour isn't triggered) but is invalid by the time we make the request to Editor API. This change reduces the risk of this happening by refreshing the token if it expires in the next 60 seconds. [1]: https://github.com/RaspberryPiFoundation/experience-cs/issues/914
1 parent f9bebfe commit 4fc74a4

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

lib/rpi_auth/controllers/auto_refreshing_token.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
module RpiAuth
66
module Controllers
77
module AutoRefreshingToken
8+
REFRESH_WINDOW_IN_SECONDS = 60
9+
810
extend ActiveSupport::Concern
911

1012
include CurrentUser
@@ -18,7 +20,7 @@ module AutoRefreshingToken
1820
def refresh_credentials_if_needed
1921
return unless current_user
2022

21-
return if Time.now.to_i < current_user.expires_at
23+
return if Time.now.to_i + REFRESH_WINDOW_IN_SECONDS <= current_user.expires_at
2224

2325
current_user.refresh_credentials!
2426
self.current_user = current_user

spec/dummy/spec/requests/refresh_credentials_spec.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,15 @@
6363
log_in(user:)
6464
end
6565

66-
context 'when the access token has not expired' do
67-
let(:expires_at) { 10.seconds.from_now }
66+
context 'when the access token is valid for at least another 60 seconds' do
67+
let(:expires_at) { 60.seconds.from_now }
6868

6969
it_behaves_like 'the user is logged in'
7070
it_behaves_like 'there is no attempt to renew the token'
7171
end
7272

73-
context 'when the access token has expired' do
74-
let(:expires_at) { 10.seconds.ago }
73+
context 'when the access token expires in the next 60 seconds' do
74+
let(:expires_at) { 59.seconds.from_now }
7575

7676
before do
7777
allow(stub_oauth_client).to receive(:refresh_credentials).with(any_args).and_return({ access_token: 'foo',

0 commit comments

Comments
 (0)