Rainbow logo
RainbowKit
2.2.10

自定義認證

自定義認證

連接到您自己的認證後端

雖然 RainbowKit 提供 第一流的支持以太坊和 NextAuth 的登入,您也可以整合自定義後端和訊息格式。

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

例如,我們可以製作一個讓我們能夠使用以太坊登入來針對某些自定義 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');
},
});

假設您的應用程式已經在某種程度上管理身份驗證生命週期,您可以將當前身份驗證狀態與自定義適配器一起傳遞給 RainbowKitAuthenticationProvider,包裹您的現有 RainbowKitProvider

import { createAuthenticationAdapter, RainbowKitAuthenticationProvider, RainbowKitProvider, } from '@rainbow-me/rainbowkit';
import { AppProps } from 'next/app';
import { WagmiProvider } from 'wagmi';
import { QueryClientProvider, QueryClient, } 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>
);
}

如果您已經走到這一步,並為現有的開源身份驗證庫創建了一個適配器,請考慮創建一個供他人使用的套件!