Is OAuth Thread Safe?
Solution 1:
Oauth is a protocol. It depends on a particular implementation whether or not that implementation is "thread safe".
Oauth2 != Oauth: How is OAuth 2 different from OAuth 1?
And REST APIs (like the one you cited) are inherently stateless, so there's really no question of "thread safety".
Finally, here's a good discussion on how to share an OAuth2 credential (that is, once you've established the credential) between multithreaded applications:
In multithreaded applications, the credential should be shared between threads. Refreshing of the credential should be performed synchronously to avoid a race condition.
The client libraries make sharing a credential across threads straightforward. Each client library has a session (or user) object which is constructed with a credential that it reuses throughout its lifetime. To share the credential across threads, simply construct each session using the same credential. In all client libraries, the credential is a thread-safe object and refreshes itself synchronously when its access token expires.
For example, in the Java client library, you would create a Credential as a singleton and share it across all sessions.
Solution 2:
I have some issues with oauth grant_type password flow.
When my app make a request to a protected resource it, using a ExchangeFilterFunction in a spring WebClient, make a request to obtain a access_token. If access_token is expired the app make a new request.
The problem is: in my implementation, if a thread detect a expired access_token it make a request to obtain a new token, in the meantime, other threads will do the same and N threads may at the same be trying to get a new access_token.
The fastest and most primitive way to solve this problem is blocking (e.g. syncrhonized keyword in java) the code snippet that gets a new token from the other threads, in this way only one request is made, but this will block all threads. When the first thread receives the new token, the other threads will be released, but now they will no longer need to make the request because they will detect a valid token.
As stated earlier, this is an implementation-specific tweak. I don't know if spring-security takes that care, but as far as I know, there's nothing in the oauth protocol specifying how to handle this.