Esc

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:

  1. Call the authenticate method
  2. Session is validated internally and a JWT is issued for your origin
  3. Send this JWT to your server
  4. Validate against our servers to extract the address
  5. Issue your own session
Client
MOSS wallet
MOSS API
Partner
  1. Client to MOSS wallet: Call authenticate

  2. MOSS wallet to MOSS API: Validate the session

  3. MOSS API to MOSS wallet: JWT for your origin

  4. MOSS wallet to Client: JWT for your origin

  5. Client to Partner: Send the JWT

  6. Partner to MOSS API: Validate the JWT

  7. MOSS API to Partner: Wallet address

  8. 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 }),
    });
}

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