Rainbow logo
RainbowKit
2.2.10

Authentification Personnalisée

Authentification Personnalisée

Connectez-vous à votre propre back-end d'authentification

Bien que RainbowKit fournisse un support de premier ordre pour Sign-In with Ethereum et NextAuth, vous pouvez également intégrer avec des back-ends et des formats de message personnalisés.

Commencez par créer un adaptateur d'authentification. Cela permet à RainbowKit de créer/préparer des messages et de communiquer avec votre back-end.

Par exemple, nous pourrions créer un adaptateur d'authentification qui nous permet d'utiliser Sign-In with Ethereum avec certains points d'API personnalisés, comme 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');
},
});

En supposant que votre application gère déjà le cycle de vie de l'authentification d'une manière ou d'une autre, vous pouvez transmettre le statut actuel de l'authentification avec votre adaptateur personnalisé à RainbowKitAuthenticationProvider, enveloppant votre RainbowKitProvider existant.

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

Si vous êtes arrivé jusqu'ici et que vous avez créé un adaptateur pour une bibliothèque d'authentification open source existante, envisagez de créer un package pour que d'autres puissent l'utiliser !