Refresh token grant race condition

Created on 8 January 2025, 3 months ago

Problem/Motivation

There is a race condition when making multiple simultaneous requests to the /oauth/token endpoint using the refresh token grant, where multiple new access/refresh tokens are being generated until the refresh token of the grant request is revoked in the database.

This problem can arise especially in web frontend applications where multiple requests may be triggered at the same time leading to a token refresh in case the access token is expired.

Steps to reproduce

  • Get a refresh token of a client application
  • Run the bash script down below (and fill in the variable values)
  • Look at the script output. On my machine the first 4 requests get status code 200, the 5th gets 401
  • Check created tokens in Drupal at /admin/config/people/simple_oauth/oauth2_token. A new access and refresh token has been created for each request leading to response code 200
refresh_token="__value-of-refresh-token__"
client_id="__client-id__"
client_secret="__client-secret__"

# Refresh the token pair.
function refresh() {
  res=$(curl -XPOST -d "client_id=$client_id&client_secret=$client_secret&grant_type=refresh_token&refresh_token=$refresh_token" https://my-drupal-site.com/oauth/token --silent -o /dev/null -w "%{http_code}")

  echo "Token refresh status: $res"
}

for i in {1..5}; do
  refresh &
done

wait

Proposed resolution

Use the Drupal lock service to make sure that only one request with the same body is handled at a time and make subsequent requests with the same content wait until the first has been handled.

This does indeed increase request times if waiting for the lock to be released, but only if another request with exactly the same body is currently being processed, meaning a token request of one user will never block the token request of another.

🐛 Bug report
Status

Active

Version

6.0

Component

Code

Created by

🇦🇹Austria chfoidl Salzburg

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024