Authentication
MOSS comes pre-packaged with a mechanism to authenticate a user server side from the client using a JWT issued from our servers.
This optimises your onboarding flows by not prompting a user to sign a SIWE message during login by reducing the number of screens and actions a user must take.
The high level flow is:
- Call the
authenticatemethod - Session is validated internally and a JWT is issued for your origin
- Send this JWT to your server
- Validate against our servers to extract the address
- Issue your own session
Client
MOSS wallet
MOSS API
Partner
Client to MOSS wallet: Call
authenticateMOSS wallet to MOSS API: Validate the session
MOSS API to MOSS wallet: JWT for your origin
MOSS wallet to Client: JWT for your origin
Client to Partner: Send the JWT
Partner to MOSS API: Validate the JWT
MOSS API to Partner: Wallet address
Partner to Client: Your own session
In practice, this looks like the following on your client:
import { mega } from '@megaeth-labs/wallet-sdk';
const auth = await mega.authenticate();
if (auth.status === 'success' && auth.jwt) {
// Send the token to your server to verify and start your own session.
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: auth.jwt }),
});
}import { useAuthenticate } from '@megaeth-labs/wallet-sdk-react';
export default function SignInButton() {
const { mutate: authenticate, isPending } = useAuthenticate({
onSuccess: async (auth) => {
if (auth.status !== 'success' || !auth.jwt) return;
// Send the token to your server to verify and start your own session.
await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: auth.jwt }),
});
},
});
return (
<button onClick={() => authenticate()} disabled={isPending}>
Sign in
</button>
);
}import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { useAccount } from 'wagmi';
export default function SignInButton() {
const { connector } = useAccount();
async function authenticate() {
const provider = (await connector?.getProvider()) as MegaWalletProvider;
const { jwt } = await provider.authenticate();
// Send the token to your server to verify and start your own session.
await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: jwt }),
});
}
return (
<button onClick={authenticate} disabled={!connector}>
Sign in
</button>
);
}And this validation on your server:
tsserver.ts
// Your app's host as the browser sees it: no scheme, and any port included.
// The token is bound to it, so a token issued for another app won't verify.
const APP_HOST = 'app.example.com';
export async function verifyMossToken(token: string): Promise<`0x${string}`> {
const url = new URL('https://wallet-api.megaeth.com/v1/partner-auth/verify');
url.searchParams.set('origin', APP_HOST);
url.searchParams.set('token', token);
const response = await fetch(url);
// Fails when the token is invalid, has expired (tokens last a day)
// or was issued for a different host.
if (!response.ok) throw new Error('Could not verify the MOSS token');
const { walletAddress } = await response.json();
return walletAddress;
}
// POST /api/login
export async function login(request: Request): Promise<Response> {
const { token } = await request.json();
let walletAddress: `0x${string}`;
try {
walletAddress = await verifyMossToken(token);
} catch {
return new Response('Unauthorised', { status: 401 });
}
// Issue your own session for walletAddress, for example a cookie.
return Response.json({ walletAddress });
}