Next.js 使用 MoneyButton 处理 0Auth 授权

Next.js handle 0Auth authorization with MoneyButton

我正在尝试使用 MoneyButton API 为我的 Next.js 应用实施 0Auth 用户授权。我可以使用 client.requestAuthorization('auth.user_identity:read','http://localhost:3000'); 触发授权请求 它顺利地将我重定向到 MoneyButton 许可同意并使用 URL -> ?code=6aa72eef702eb710cd22715d797cf7d27e06532a&state=38984b9d-3af0-48f1-8b5f-3fa47f4dfd9d

中的 codestate 参数返回到我的应用程序

client.handleAuthorizationResponse(); 方法来处理响应。该方法自动从查询参数中获取令牌并设置客户端的内部状态以使用它们。它还将凭据保存在本地存储中,因此用户在关闭浏览器时仍会使用 Money Button 保持登录状态。 但不幸的是,在重定向回我的应用程序后,我不知道如何使用此方法。我在 Authuser 函数中使用它,但是 requestAuthorization 触发重定向到 moneybutton,所以函数的其余部分没有执行。重定向回应用后如何使用handleAuthorization?

https://docs.moneybutton.com/docs/api/auth/api-auth-jsclient.html - 这是 MoneyButton 文档

我也在考虑在 NextAuth.js 中将 MoneyButton 添加为自定义 0Auth 提供程序,以便将来更快地集成。

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)
}

您需要确保 client.handleAuthorizationResponse(); 是 运行 客户端(而不是服务器端呈现)在 moneybutton 身份验证重定向回来后:

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