Reputation: 89
I am trying to implement a OAuth2 flow for a for a Single Page Webapp, but I don't know how to handle the Frontend/ Javascript redirects side.
I have the backend figured out: I'm using a library that does all the work and exposes 2 routes:
/auth/authorize
returns a json response like this:
{ "authorization_url": "https://github.com/login/oauth/authorize?response_type=code&client_id=d263f54&redirect_uri=http%3A%2F%2Fxxx&state=eyJ0eXAiOiJkdjsfkj&scope=read" }
/auth/callback
that when called back as the redirect_uri
by the OAuth provider (Github here), either returns a json response like
{"access_token":"jhfgkjhdfkjghkdhgkdhgfd","token_type":"bearer"}
(if Bearer authentication is used), or simply null
(if Cookie authentication is used. In that case the cookie is correcly set on the browser)
How should I handle this on the frontend though?
Whe a user clicks the Login button, I can redirect them to Oauth provider login page with something like
window.open(axios.get('/auth/authorize').data.authorization_url);
, no problem.
But then, if in my OAuth provider I register the callback to be /auth/callback
, the user will be redirected to a page that only shows text, which is not good.
I think I am supposed to register a Frontend route as the OAuth provider callback, and that route should listen to the response from the OAuth provider, and manually forward the exact same response to the backend's auth/callback
.
How do you do this in Axios/Javascript?
Is there a correct/best practice way to do this?
Thanks!
(as additional infos, the backend library I'm using is FastAPI-Users and frontend is in Vuejs)
Upvotes: 0
Views: 4696
Reputation: 29218
The way I've always done it is to make the redirect URI the base path of the app, then process the OAuth response when the app loads. Here is some example React code of mine that does this.
I combine this with pre and post login code, which deals with removing login response URLs from the browser history and restoring state, such as the original apication path. so that deep linking works.
MULTI TAB BROWSING
The above technique of a handlePageLoad
method is also useful for setting up the authentication state, if the user opens a new browser tab or reloads the page. So I think it works better to run it from any path, rather than to use a specific route.
Upvotes: 1