I have a React frontend, that logs in into an external identity provider using a Spring OAuth2 backend. I have an issue finding a good solution on how to retrieve the refresh and access token safely back to frontend when login is done.
When login is done, the spring app sends back a redirect back to the frontend app, but at this point the only place the token is available is in the security context in the spring backend. So to retrieve tokens I now have to send an additional request to the backend to get the tokens from the security context.
I wonder if it would be safe to just return the refresh token directly in the redirect url (query parameter) back to the application? If not, which issues would one face?
It would not be safe, since the refresh token would then be included in both the browser history and also in HTTP logs. OAuth intentionally requires two stages as follows, and a lot of experts have thought this through from a security viewpoint:
An authorization redirect returns a 'one time use' authorization code to the app after the user authenticates. This is done in the browser, where there is the potential for certain types of attack and interception.
Next the app sends an authorization code grant message, to swap the code for tokens. Tokens are returned in the response body and are not included in server logs or the browser history.
With OAuth I would always recommend sticking to standards based messages, as in my Messages Blog Post. In most systems you cannot change these messages, which is a good thing. Doing so can reduce security and also make your applications less portable.