udibo / oauth2_server

A standards compliant implementation of an OAuth 2.0 authorization server with PKCE support.
MIT License
20 stars 4 forks source link

Add OAuth2Client for simplifying requests to OAuth2 resource and authorization servers #17

Open KyleJune opened 2 years ago

KyleJune commented 2 years ago

Currently the example manually refreshes token when it is expired. Create an OAuth2Client object that can handle refreshing tokens and handling authorization flow. The client should have a fetch function to make it easier to make fetch requests to API endpoints that use OAuth2 for authentication.

Add getClientForRequest to server and oak adapter. Add getClientForContext to oak adapter. This will behave similar to getTokenForRequest except it will instead return an OAuth2Client that is ready to make requests for the user. For this to work, the server would need to take some configuration options like the authorizeUrl and tokenUrl.

KyleJune commented 2 years ago

For refreshing tokens, use local storage to create a lock to prevent the client from sending multiple refresh token requests at the same time. For requests made from the same tab, the refresh token request's promise can be shared instead of using the local storage lock so that it will be able to continue the moment it receives a new access token. For other tabs, they will need to use an interval for checking the local storage lock. Once the lock is released, they can start making requests again with the new access token cookie.

This will be needed to prevent the refresh tokens from getting revoked due to token replay. Other OAuth2 providers like Okta and Auth0 have a refresh token grace period to avoid that issue.

https://developer.okta.com/docs/guides/refresh-tokens/main/#grace-period-for-token-rotation https://auth0.com/docs/security/tokens/refresh-tokens/configure-refresh-token-rotation

KyleJune commented 2 years ago

OAuth2Client should not use local storage to create a lock. Instead use the Web Locks API.

For use on the server side, leave lock implementation up to the user. I plan on using Redis RedLock or a postgres advisory lock.

KyleJune commented 1 year ago

We should refresh tokens 5 seconds before they expire. That way if there are latency issues, they won't result in requests being denied for using a token that expired by the time the request reached the server. Have it possible to configure this option by ms. With 0 meaning it would only refresh if the token is expired at the time of making the request.