Search code examples
javascriptreactjsoauth-2.0oauthnext.js

Next.js handle 0Auth authorization with MoneyButton


I am attempting to implement 0Auth user authorization for my Next.js app using MoneyButton API. I am able to trigger the authorization request with client.requestAuthorization('auth.user_identity:read','http://localhost:3000'); And it works smoothly redirecting me to MoneyButton permission consent and back to my app with the code and state params in URL -> ?code=6aa72eef702eb710cd22715d797cf7d27e06532a&state=38984b9d-3af0-48f1-8b5f-3fa47f4dfd9d

There is client.handleAuthorizationResponse(); method for handle the response. That method automatically gets the tokens from the query parameters and set the internal state of the client to use them. Also it saves the credentials in local storage, so the user stays logged in with Money Button if they close the browser. But unfortunately i don't know how to use this method after being redirected back to my app. I am using it in Authuser function, but requestAuthorization triggers redirect to moneybutton, so rest of the function is not executed. How to use handleAuthorization after being redirected back to application?

https://docs.moneybutton.com/docs/api/auth/api-auth-jsclient.html - here are the MoneyButton docs

I am also considering to add MoneyButton as custom 0Auth provider in NextAuth.js to make integrations faster in the future.

Authuser.js

const { MoneyButtonClient } = require('@moneybutton/api-client')

export default function Authuser () {
    const client = new MoneyButtonClient('MYAPP_OAUTH_IDENTIFIER_CODE');
   
    client.requestAuthorization('auth.user_identity:read','http://localhost:3000');
    client.handleAuthorizationResponse();
    const refreshToken = client.getRefreshToken();
    client.setRefreshToken(refreshToken)
}

Solution

  • You need to make sure that client.handleAuthorizationResponse(); is run client side (not server side render) after the moneybutton auth has redirected back:

    if ((new URLSearchParams(window.location.search)).has('code')) {
      await client.handleAuthorizationResponse()
      const accessToken = await client.getValidAccessToken()
      ...
    }