Rainbow logo
RainbowKit
2.2.11

カスタム認証

カスタム認証

独自の認証バックエンドに接続する

RainbowKitは、EthereumでサインインとNextAuthに対する第一級のサポートを提供しますが、独自のバックエンドやメッセージフォーマットと統合することもできます。

まず、認証アダプターを作成します。これにより、RainbowKitはメッセージを作成/準備してバックエンドと通信できます。

例として、カスタムAPIエンドポイントに対してSign-In with Ethereumを使用できる認証アダプターを作成するとします。例えば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 メッセージを構築できます。より厳密なセキュリティのために、サーバーエンドポイントは domainnonce、および issued-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>
);
}

ここまで進み、既存のオープンソース認証ライブラリに対するアダプタを作成した場合、他の人が使用できるパッケージを作成することをご検討ください!