Skip to content

Commit 8c1bc9a

Browse files
committed
Add Farcaster guides
1 parent 4d48c1e commit 8c1bc9a

4 files changed

Lines changed: 486 additions & 0 deletions

File tree

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
---
2+
title: Integrate Sign In with Farcaster with Web3Auth MPC CoreKit Web SDK
3+
image: "guides/banners/farcaster-mpc-ck-web.png"
4+
description: Learn how to use Sign In with Farcaster with Web3Auth MPC CoreKit Web SDK
5+
type: guide
6+
tags: ["@web3auth/mpc-core-kit", mpc, mpc-core-kit-web, farcaster, react, ethereum, next.js]
7+
date: May 9, 2024
8+
author: Web3Auth Team
9+
communityPortalTopicId:
10+
pinned: false
11+
---
12+
13+
### Prerequisites:
14+
15+
- Basic understanding of React and Next.js
16+
- Familiarity with JavaScript and TypeScript
17+
- Basic knowledge of authentication and JWT tokens
18+
19+
### Step 1: Install and Configure Sign In with Farcaster
20+
21+
a. **Install Dependencies**: Install `auth-kit` and its peer dependency `viem` using npm.
22+
23+
```bash
24+
npm install @farcaster/auth-kit viem
25+
```
26+
27+
Note: `auth-kit` is a React library. If you're using a different framework, take a look at the
28+
[client library](https://docs.farcaster.xyz/auth-kit/client/introduction) instead.
29+
30+
b. **Import Libraries**: Import `auth-kit` and its CSS styles into your React component.
31+
32+
```tsx
33+
import "@farcaster/auth-kit/styles.css";
34+
import { AuthKitProvider, SignInButton, useProfile } from "@farcaster/auth-kit";
35+
```
36+
37+
c. **Configure Provider**: Set up a provider with your desired configuration including the RPC URL,
38+
domain, and login URL.
39+
40+
```tsx
41+
const config = {
42+
rpcUrl: "https://mainnet.optimism.io",
43+
domain: "example.com",
44+
siweUri: "https://example.com/login",
45+
};
46+
```
47+
48+
d. **Integrate Sign-In Button**: Render the `SignInButton` component in your UI to prompt users to
49+
sign in.
50+
51+
```tsx
52+
const App = () => {
53+
return (
54+
<AuthKitProvider config={config}>
55+
{/* Your App */}
56+
<SignInButton />
57+
</AuthKitProvider>
58+
);
59+
};
60+
```
61+
62+
### Step 2: Verify Signatures on Backend
63+
64+
We will be using `NextAuth` to implement Authorization logic.
65+
66+
a. **Create a NextAuth API**: Create an API route using NextAuth to handle authentication and
67+
signature verification.
68+
69+
`pages/api/auth/[...nextauth].ts`
70+
71+
```tsx
72+
import NextAuth from "next-auth";
73+
import CredentialsProvider from "next-auth/providers/credentials";
74+
import { createAppClient, viemConnector } from "@farcaster/auth-client";
75+
```
76+
77+
b. **Authorization Logic**: Implement authorization logic to verify user signatures and credentials.
78+
79+
```tsx
80+
async authorize(credentials) {
81+
const { body: { csrfToken } } = req;
82+
83+
const appClient = createAppClient({
84+
ethereum: viemConnector(),
85+
});
86+
87+
const verifyResponse = await appClient.verifySignInMessage({
88+
message: credentials?.message as string,
89+
signature: credentials?.signature as `0x${string}`,
90+
domain: "example.com",
91+
nonce: csrfToken,
92+
});
93+
const { success, fid } = verifyResponse;
94+
95+
if (!success) {
96+
return null;
97+
}
98+
99+
return {
100+
id: fid.toString(),
101+
name: credentials?.name,
102+
image: credentials?.pfp,
103+
};
104+
},
105+
```
106+
107+
### Step 3: Generate a JWT Token using Farcaster User's data
108+
109+
a. **Create a JWT Token**: Create an API endpoint to generate JWT tokens containing user's data from
110+
Farcaster.
111+
[Follow these steps to setup your Custom Verifier with Web3Auth](https://web3auth.io/docs/auth-provider-setup/byo-jwt-provider#set-up-custom-jwt-verifier).
112+
`pages/api/login.ts`
113+
114+
```tsx
115+
import jwt from "jsonwebtoken";
116+
```
117+
118+
b. **JWT Signing**: Sign the JWT token using a
119+
[private key](https://web3auth.io/docs/auth-provider-setup/byo-jwt-provider#using-rsa-for-jwt-signing)
120+
and include necessary user data that you get from Farcaster.
121+
122+
```tsx
123+
const userData = req.body.userData;
124+
// Get RS256 key of length 2048
125+
const privateKey = process.env.PRIVATE_KEY!;
126+
127+
const jwtToken = jwt.sign(
128+
{
129+
sub: userData?.fid.toString(),
130+
name: userData?.displayName,
131+
username: userData?.username,
132+
profileImage: userData?.pfpUrl,
133+
custody: userData?.custody,
134+
aud: "w3a:farcaster-server",
135+
iss: "https://web3auth.io",
136+
iat: Math.floor(Date.now() / 1000),
137+
exp: Math.floor(Date.now() / 1000) + 60 * 60,
138+
},
139+
privateKey,
140+
{ algorithm: "RS256", keyid: "REPLACE_KEY_ID" },
141+
);
142+
```
143+
144+
### Step 4: Authenticate with Web3Auth
145+
146+
a. **Initialize Web3Auth MPC CoreKit Web SDK**: Set up Web3Auth instance and configure it with
147+
necessary parameters.
148+
149+
```tsx
150+
import { Web3AuthMPCCoreKit, WEB3AUTH_NETWORK, parseToken } from "@web3auth/mpc-core-kit";
151+
import { EthereumSigningProvider } from "@web3auth/ethereum-mpc-provider";
152+
153+
const coreKitInstance = new Web3AuthMPCCoreKit({
154+
web3AuthClientId, // Your Web3Auth Client ID
155+
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // Web3Auth Network
156+
setupProviderOnInit: false, // if needed to skip the provider setup
157+
manualSync: true, // This is the recommended approach since it allows you to control the sync process
158+
});
159+
160+
const chainConfig = {
161+
chainNamespace: CHAIN_NAMESPACES.EIP155,
162+
chainId: "0x1", // Please use 0x1 for Mainnet
163+
rpcTarget: "https://rpc.ankr.com/eth",
164+
displayName: "Ethereum Mainnet",
165+
blockExplorer: "https://etherscan.io/",
166+
ticker: "ETH",
167+
tickerName: "Ethereum",
168+
};
169+
170+
const evmProvider = new EthereumSigningProvider({ config: { chainConfig } });
171+
evmProvider.setupProvider(coreKitInstance);
172+
173+
await coreKitInstance.init();
174+
```
175+
176+
b. **Get idToken from your backend**:
177+
178+
```tsx
179+
const response = await fetch("/api/login", {
180+
method: "POST",
181+
headers: {
182+
"Content-Type": "application/json",
183+
},
184+
body: JSON.stringify({ userData: res }),
185+
});
186+
const data = await response.json();
187+
const token = data.token;
188+
```
189+
190+
c. **Initiate Web3Auth Login**:
191+
192+
Implement login functionality using the generated JWT token.
193+
194+
```tsx
195+
const login = async (idToken: any) => {
196+
// Login logic
197+
if (!coreKitInstance) {
198+
throw new Error("Web3Auth CoreKit not initialized");
199+
}
200+
const { payload } = parseToken(idToken);
201+
202+
await coreKitInstance.loginWithJWT({
203+
verifier, // Your verifier name from Web3Auth Dashboard
204+
verifierId: (payload as any).sub, // based on your setup
205+
idToken, // JWT token from your backend
206+
});
207+
if (coreKitInstance.status === COREKIT_STATUS.LOGGED_IN) {
208+
await coreKitInstance.commitChanges(); // Needed to commit for new accounts, when using manualSync: true
209+
}
210+
};
211+
```
212+
213+
### Step 5 (Optional): Additional Features
214+
215+
a. **Blockchain Interactions**: Include optional features like checking balances, signing messages,
216+
and sending transactions.
217+
218+
```tsx
219+
const getBalance = async (provider: IProvider) => {
220+
// Get balance logic
221+
};
222+
```
223+
224+
b. **Logout Functionality**: Implement logout functionality for users.
225+
226+
```tsx
227+
const logOut = async () => {
228+
await coreKitInstance.logout();
229+
await signOut();
230+
};
231+
```
232+
233+
### Full Implementation Example
234+
235+
Here's
236+
[an example of how to integrate the above steps into your Next.js application](https://github.com/shahbaz17/farcaster-next-w3a)
237+
238+
---
239+
240+
This guide should provide a clear structure and step-by-step instructions for integrating
241+
[`Sign In with Farcaster`](https://docs.farcaster.xyz/auth-kit/installation) using
242+
[Web3Auth SFA Web SDK](https://web3auth.io/docs/sdk/core-kit/sfa-web). Let me know if you need
243+
further clarification on any part!

0 commit comments

Comments
 (0)