Search code examples
node.jsreactjsoauth-2.0

Is it possible to capture an OAuth form post redirect in browser?


I am trying to integrate third-party (TP) APIs (https://api.icicidirect.com/apiuser/ICICIDirectAPIDOC.htm) in my react/node.js app. The APIs use OAuth 2 for authentication and after authentication.

The sequence of actions is something like this - a user clicks on the TP image on my react app and gets redirected to the TP's login page. After authentication, TP does a redirect with a form post. Based on my current understanding, only the backend server can host a post method where the TP can post the form. From here, it is not clear how to trigger the react app to detect that the user has logged in and render their dashboard.

I have two questions:

  1. Assuming I register a frontend URL as the redirect URL, is there a way I can capture this form post on the frontend?
  2. If #1 is not possible, what's the most elegant way of letting the frontend know that the login was successful, after receiving the redirect on the backend?

Solution

  • I would check a couple of things since it seems your app needs to use OAuth tokens as well as to sign in:

    • Is PKCE used and / or a client secret? This will determine whether you can complete the login in the browser and swap the code for tokens.

    • Can you add a response_mode=query query parameter when you trigger the redirect, which will make the response a GET (if the provider supports it).

    Q1

    The usual solution is to return the authorization result on this type of URL, which is SPA friendly. The browser cannot receive POST requests.

    The SPA can then perform one of these actions and get tokens:

    • Exchange the code for tokens if PKCE (a runtime secret) is used
    • Otherwise proxy the request via an API, which attaches the client secret

    Q2

    If the provider only supports POST responses you can can write a small amount of code in the web host (as a workaround) when it serves the index.html page. This could check whether it is a login response, and if so trigger a redirect with the above query parameters.

    WEB HOST RESPONSE PROCESSING

    Do the login response processing and code exchange in the web host, then redirect the SPA to a location such as https://www.example.com/loggedin, which will notify the SPA so that it can update its UI state.

    ALTERNATIVE OPTION: OUT OF INTEREST

    The above could require quite a bit of code in the web host, which could potentially impact your web deployment options, eg if you wanted to serve web static content from a Content Delivery Network.

    So another option the web host could use is to just perform a redirect to https://www.example.com?code=xxx&state=yyy. The SPA could then call an API to complete the OAuth processing. This requires more security due diligence (eg ensure that PKCE is used), but is how a Back End for Front End SPA solution would work.