# 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: Call `authenticate`
- MOSS wallet → MOSS API: Validate the session
- MOSS API → MOSS wallet: JWT for your origin
- MOSS wallet → Client: JWT for your origin
- Client → Partner: Send the JWT
- Partner → MOSS API: Validate the JWT
- MOSS API → Partner: Wallet address
- Partner → Client: Your own session

In practice, this looks like the following on your client:

```ts title="Pure JS"
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 }),
    });
}
```

```tsx title="React"
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>
    );
}
```

```tsx title="Wagmi"
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:

```ts title="server.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 });
}
```
