Rainbow logo
RainbowKit
2.2.11

自訂驗證

自訂驗證

連接到您自己的驗證後端

雖然 RainbowKit 提供與 Ethereum 和 NextAuth 的頭等支持,您也可以與自訂的後端和消息格式集成。

首先創建一個驗證適配器。這允許 RainbowKit 創建/準備消息並與您的後端進行通信。

例如,我們可以製作一個驗證適配器,讓我們可以使用 Ethereum 登入 針對一些自訂 API 端點,如 iron-session

import { createAuthenticationAdapter } from '@rainbow-me/rainbowkit';
import { createSiweMessage } from 'viem/siwe';
const authenticationAdapter = createAuthenticationAdapter({
getNonce: async () => {
const response = await fetch('/api/nonce');
return await response.text();
},
createMessage: ({ nonce, address, chainId }) => {
return createSiweMessage({
domain: window.location.host,
address,
statement: 'Sign in with Ethereum to the app.',
uri: window.location.origin,
version: '1',
chainId,
nonce,
});
},
verify: async ({ message, signature }) => {
const verifyRes = await fetch('/api/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message, signature }),
});
return Boolean(verifyRes.ok);
},
signOut: async () => {
await fetch('/api/logout');
},
});

createMessage 亦支持返回 Promise,讓您能夠在伺服器上構建 EIP-4361 訊息。為了更嚴格的安全性,伺服器端應推導或驗證安全性關鍵字段,如 domainnonceissued-at 時間戳,而不是信任由客戶端提供的值。詳情參考 SIWE 文件

createMessage: async ({ address, chainId }) => {
const response = await fetch('/api/siwe/message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ address, chainId }),
});
if (!response.ok) {
throw new Error('Failed to create message');
}
return await response.text();
},

假設您的應用程式已經設法管理驗證生命週期,您可以將當前驗證狀態與自訂適配器一起傳遞給 RainbowKitAuthenticationProvider,包裝您現有的 RainbowKitProvider

import { createAuthenticationAdapter, RainbowKitAuthenticationProvider, RainbowKitProvider, } from '@rainbow-me/rainbowkit';
import { AppProps } from 'next/app';
import { WagmiProvider } from 'wagmi';
import { QueryClient, QueryClientProvider, } from '@tanstack/react-query';
const authenticationAdapter = createAuthenticationAdapter({
/* See above... */
});
const queryClient = new QueryClient();
export default function App({ Component, pageProps }: AppProps) {
// You'll need to resolve AUTHENTICATION_STATUS here
// using your application's authentication system.
// It needs to be either 'loading' (during initial load),
// 'unauthenticated' or 'authenticated'.
return (
<WagmiProvider {...etc}>
<QueryClientProvider client={queryClient}>
<RainbowKitAuthenticationProvider adapter={authenticationAdapter} status={AUTHENTICATION_STATUS} >
<RainbowKitProvider {...etc}>
<Component {...pageProps} />
</RainbowKitProvider>
</RainbowKitAuthenticationProvider>
</QueryClientProvider>
</WagmiProvider>
);
}

如果您已經做到這麼多,並為現有的開源驗證庫創建了一個適配器,請考慮創建一個包供其他人使用!