What is the best approach in terms of security when making a request on a resource server that uses Oauth2 ?
With four actors :
First approach: Use the client server as a proxy to access the resource server from the Javascript client, and not expose the JWT token.
Second approach: Expose the JWT token and access the resource server directly from the JavaScript client.
1: JAVASCRIPT ONLY APPROACH
This is used when you want to follow an SPA architecture, with no web back end and deploying the SPA's static content to a content delivery network. But it has these issues and is no longer really viable:
2: REFRESH TOKEN IN A COOKIE APPROACH
A good next step is to store refresh tokens strongly encrypted in an HTTP only secure cookie, with only short lived access tokens in the browser:
This is a pretty secure model, but there are still some concerns about access tokens being intercepted, either at rest or in flight. The main mitigations are to keep access tokens short lived, unreadable and store them only in memory.
3: NO TOKENS IN THE BROWSER APPROACH
It is common once you have implemented this option to also use cookies for access tokens, which is currently considered the browser best practice:
SameSite=strict
cookies in the browserBrowser exploits to send secure cookies via session hijacking are still possible so it is recommended to also follow best practices to protect against XSS risks.
SEPARATING WEB AND API CONCERNS
You can get recommended security and also an SPA architecture by implementing Website security in an API, which is an evolution of the third approach. It is a tricky flow, but if interested, have a look at the Curity resources on this topic: