Micoloth
Micoloth

Reputation: 89

How to handle OAuth2 redirect on the frontend side

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:

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

Answers (1)

Gary Archer
Gary Archer

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

Related Questions