> ## Documentation Index
> Fetch the complete documentation index at: https://docs.privy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Authorizing actions with granular MFA

> Authorize wallet actions that require MFA with the React SDK or a server SDK.

To authorize an action that requires MFA, the user signs it with a user key that records a completed MFA verification.

## MFA verification

**NodeJS**

Your app's server verifies the user's MFA, then passes the MFA token with the user's JWT in `user_auth`. The SDK exchanges them for a user key that records the MFA, and signs the request with it. The user must be enrolled in MFA first. See [enrollment with server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#enrollment).

Send the user an SMS code, then verify it to get an MFA token. TOTP and passkeys work the same way. See [server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#verification).

This requires `@privy-io/node` version `0.39.0` or later.

```ts {skip-check} theme={"system"}
// Sends a 6-digit code to the user's enrolled phone number
await privy.users().mfa.sms.verification.init(userId, {user_jwt: userJwt});

// After the user receives the code
const {token: mfaToken} = await privy.users().mfa.sms.verification.verify(userId, {
  code: '123456',
  user_jwt: userJwt
});

// Pass this as the authorization_context of any wallet request
const authorizationContext = {
  user_auth: [{user_jwt: userJwt, mfa_token: mfaToken}]
};
```

The MFA token lasts for the cache duration. Pass the latest token on every request that may require MFA.

**Java**

Your app's server verifies the user's MFA, then passes the MFA token with the user's JWT in `user_auth`. The SDK exchanges them for a user key that records the MFA, and signs the request with it. The user must be enrolled in MFA first. See [enrollment with server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#enrollment).

Send the user an SMS code, then verify it to get an MFA token. TOTP and passkeys work the same way. See [server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#verification).

This requires `privy-java` version `0.61.0` or later. The MFA methods are on `PrivyApiClient`.

```java theme={"system"}
PrivyApiClient privyApiClient = PrivyApiClient.builder()
    .privyAppId("insert-app-id")
    .privyAppSecret("insert-app-secret")
    .build();

// Sends a 6-digit code to the user's enrolled phone number
privyApiClient.users().mfa().sms().verification().init(userId, userJwt);

// After the user receives the code
String mfaToken = privyApiClient.users().mfa().sms().verification()
    .verify(userId, userJwt, SmsMfaVerifyRequestBody.builder().code("123456").build())
    .mfaVerificationResponse()
    .orElseThrow()
    .token();

// Pass this to any wallet method
AuthorizationContext authorizationContext = AuthorizationContext.builder()
    .addUserAuth(userJwt, mfaToken)
    .build();
```

The MFA token lasts for the cache duration. Pass the latest token on every request that may require MFA.

**Go**

Your app's server verifies the user's MFA, then passes the MFA token with the user's JWT in `user_auth`. The SDK exchanges them for a user key that records the MFA, and signs the request with it. The user must be enrolled in MFA first. See [enrollment with server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#enrollment).

Send the user an SMS code, then verify it to get an MFA token. TOTP and passkeys work the same way. See [server-side MFA](https://docs.privy.io/authentication/user-authentication/mfa/server-side.md#verification).

This requires `github.com/privy-io/go-sdk` version `0.17.0` or later.

```go theme={"system"}
import "github.com/privy-io/go-sdk/authorization"

// Sends a 6-digit code to the user's enrolled phone number
_, err := client.Users.Mfa.SMS.Verification.Init(context.Background(), userID, privy.UserMfaSMSVerificationInitParams{
    UserJwt: userJwt,
})
if err != nil {
    log.Fatalf("failed to send MFA code: %v", err)
}

// After the user receives the code
verification, err := client.Users.Mfa.SMS.Verification.Verify(context.Background(), userID, privy.UserMfaSMSVerificationVerifyParams{
    SMSMfaVerifyRequestBody: privy.SMSMfaVerifyRequestBody{Code: "123456"},
    UserJwt:                 userJwt,
})
if err != nil {
    log.Fatalf("failed to verify MFA code: %v", err)
}

// Pass this to any wallet method with privy.WithAuthorizationContext
authorizationContext := &authorization.AuthorizationContext{
    UserAuth: []authorization.UserAuth{{UserJwt: userJwt, MfaToken: verification.Token}},
}
```

The MFA token lasts for the cache duration. Pass the latest token on every request that may require MFA.

**React**

The React SDK's wallet hooks prompt for MFA when a request requires it. See [setup](https://docs.privy.io/authentication/user-authentication/mfa/granular/setup.md#add-the-policy-to-a-wallet). `generateAuthorizationSignature` from `useAuthorizationSignature` does not prompt. With granular MFA, it signs with a user key that records no MFA.

Call `promptMfa` from `useMfa` before you generate the signature. Once the user completes MFA, the next signature uses a user key that records the MFA. `promptMfa` returns without a prompt if the user has no MFA methods, so enroll the user first.

## Examples

Each example shows a policy that requires MFA for the action, then the request.

### Export a wallet

Exporting a private key or seed phrase requires MFA. This is the policy from [setup](https://docs.privy.io/authentication/user-authentication/mfa/granular/setup.md#create-a-policy).

```ts {skip-check} theme={"system"}
{
    "version": "1.0",
    "name": "Require MFA for wallet export",
    "chain_type": "ethereum",
    "rules": [
        {
            "name": "Require MFA for private key export",
            "method": "exportPrivateKey",
            "conditions": [],
            "action": "ALLOW_WITH_MFA"
        },
        {
            "name": "Require MFA for seed phrase export",
            "method": "exportSeedPhrase",
            "conditions": [],
            "action": "ALLOW_WITH_MFA"
        },
        {
            "name": "Allow everything else",
            "method": "*",
            "conditions": [],
            "action": "ALLOW"
        }
    ]
}
```

**NodeJS**

The SDK decrypts the exported key for you.

```ts {skip-check} theme={"system"}
const {private_key} = await privy.wallets().exportPrivateKey(walletId, {
  authorization_context: authorizationContext
});
```

**Java**

The SDK decrypts the exported key for you.

```java theme={"system"}
String privateKey = privyClient.wallets().export(walletId, authorizationContext);
```

**Go**

The SDK decrypts the exported key for you.

```go theme={"system"}
exported, err := client.Wallets.Export(
    context.Background(),
    walletID,
    privy.WithAuthorizationContext(authorizationContext),
)
if err != nil {
    log.Fatalf("failed to export wallet: %v", err)
}

privateKey := exported.PrivateKey
```

**React**

```tsx theme={"system"}
import {useExportWallet} from '@privy-io/react-auth';

const {exportWallet} = useExportWallet();

await exportWallet({address: 'insert-wallet-address'});
```

### Sign a message

Signing any message requires MFA.

```ts {skip-check} theme={"system"}
{
    "version": "1.0",
    "name": "Require MFA for message signing",
    "chain_type": "ethereum",
    "rules": [
        {
            "name": "Require MFA to sign messages",
            "method": "personal_sign",
            "conditions": [],
            "action": "ALLOW_WITH_MFA"
        },
        {
            "name": "Allow everything else",
            "method": "*",
            "conditions": [],
            "action": "ALLOW"
        }
    ]
}
```

**NodeJS**

```ts {skip-check} theme={"system"}
const {signature} = await privy.wallets().ethereum().signMessage(walletId, {
  message: 'Hello, world!',
  authorization_context: authorizationContext
});
```

**Java**

```java theme={"system"}
EthereumPersonalSignRpcResponseData response = privyClient
    .wallets()
    .ethereum()
    .signMessage(walletId, "Hello, world!", authorizationContext);
```

**Go**

```go theme={"system"}
response, err := client.Wallets.Ethereum.SignMessage(
    context.Background(),
    walletID,
    "Hello, world!",
    privy.WithAuthorizationContext(authorizationContext),
)
if err != nil {
    log.Fatalf("failed to sign message: %v", err)
}
```

**React**

```tsx theme={"system"}
import {useSignMessage} from '@privy-io/react-auth';

const {signMessage} = useSignMessage();

const {signature} = await signMessage(
  {message: 'Hello, world!'},
  {address: 'insert-wallet-address'}
);
```

### Send a transaction

Sending more than 1 ETH requires MFA.

```ts {skip-check} theme={"system"}
{
    "version": "1.0",
    "name": "Require MFA for large ETH transfers",
    "chain_type": "ethereum",
    "rules": [
        {
            "name": "Require MFA for transfers over 1 ETH",
            "method": "eth_sendTransaction",
            "conditions": [
                {
                    "field_source": "ethereum_transaction",
                    "field": "value",
                    "operator": "gt",
                    "value": "0xDE0B6B3A7640000" // 1 ETH in wei
                }
            ],
            "action": "ALLOW_WITH_MFA"
        },
        {
            "name": "Allow everything else",
            "method": "*",
            "conditions": [],
            "action": "ALLOW"
        }
    ]
}
```

**NodeJS**

```ts {skip-check} theme={"system"}
const {hash} = await privy
  .wallets()
  .ethereum()
  .sendTransaction(walletId, {
    caip2: 'eip155:8453',
    params: {
      transaction: {
        to: '0xRecipientAddress',
        value: '0x1BC16D674EC80000', // 2 ETH in wei
        chain_id: 8453
      }
    },
    authorization_context: authorizationContext
  });
```

**Java**

```java theme={"system"}
UnsignedStandardEthereumTransaction transaction = UnsignedStandardEthereumTransaction.builder()
    .to("0xRecipientAddress")
    .value(Quantity.of("0x1BC16D674EC80000")) // 2 ETH in wei
    .chainId(Quantity.of(8453))
    .build();

EthereumSendTransactionRpcResponseData response = privyClient
    .wallets()
    .ethereum()
    .sendTransaction(walletId, "eip155:8453", transaction, authorizationContext);
```

**Go**

```go theme={"system"}
response, err := client.Wallets.Ethereum.SendTransaction(
    context.Background(),
    walletID,
    "eip155:8453",
    privy.EthereumSendTransactionRpcInputParams{
        Transaction: privy.UnsignedEthereumTransactionUnion{
            OfUnsignedStandardEthereumTransaction: &privy.UnsignedStandardEthereumTransaction{
                To:      privy.String("0xRecipientAddress"),
                Value:   privy.QuantityUnion{OfString: privy.String("0x1BC16D674EC80000")}, // 2 ETH in wei
                ChainID: privy.QuantityUnion{OfInt: privy.Int(8453)},
            },
        },
    },
    privy.WithAuthorizationContext(authorizationContext),
)
if err != nil {
    log.Fatalf("failed to send transaction: %v", err)
}
```

**React**

```tsx theme={"system"}
import {useSendTransaction} from '@privy-io/react-auth';

const {sendTransaction} = useSendTransaction();

const {hash} = await sendTransaction(
  {
    to: '0xRecipientAddress',
    value: '0x1BC16D674EC80000', // 2 ETH in wei
    chainId: 8453
  },
  {address: 'insert-wallet-address'}
);
```

### Update a wallet

Changing a user-owned wallet's policies or signers requires the user's MFA, with or without a policy. See [resource updates](https://docs.privy.io/authentication/user-authentication/mfa/granular/when-mfa-is-required.md#resource-updates).

**NodeJS**

```ts {skip-check} theme={"system"}
const wallet = await privy.wallets().update(walletId, {
  policy_ids: [policyId],
  authorization_context: authorizationContext
});
```

**Java**

```java theme={"system"}
WalletUpdateResponse response = privyClient.wallets().update(
    walletId,
    WalletUpdateRequestBody.builder().policyIds(List.of(policyId)).build(),
    authorizationContext);
```

**Go**

```go theme={"system"}
wallet, err := client.Wallets.Update(
    context.Background(),
    walletID,
    privy.WalletUpdateParams{
        WalletUpdateRequestBody: privy.WalletUpdateRequestBody{
            PolicyIDs: []string{policyID},
        },
    },
    privy.WithAuthorizationContext(authorizationContext),
)
if err != nil {
    log.Fatalf("failed to update wallet: %v", err)
}
```

**React**

```tsx theme={"system"}
import {useUpdateWallet} from '@privy-io/react-auth';

const {updateWallet} = useUpdateWallet();

await updateWallet('insert-wallet-id', {
  policy_ids: [policyId]
});
```

**React**

### Generating authorization signatures

This example signs the 2 ETH transfer from [send a transaction](#send-a-transaction) as a sponsored request. Your server submits it.

```tsx theme={"system"}
import {useAuthorizationSignature, useMfa} from '@privy-io/react-auth';

const {promptMfa} = useMfa();
const {generateAuthorizationSignature} = useAuthorizationSignature();

const body = {
  method: 'eth_sendTransaction',
  caip2: 'eip155:8453',
  sponsor: true,
  params: {
    transaction: {
      to: '0xRecipientAddress',
      value: '0x1BC16D674EC80000', // 2 ETH in wei
      chain_id: 8453
    }
  }
};

// Prompts the user to verify with an enrolled MFA method
await promptMfa();

// Signs with a user key that records the MFA
const {signature} = await generateAuthorizationSignature({
  version: 1,
  method: 'POST',
  url: 'https://api.privy.io/v1/wallets/insert-wallet-id/rpc',
  body,
  headers: {'privy-app-id': 'insert-app-id'}
});
```

Send `body` and `signature` to your server. Your server sends the same body to the RPC endpoint with your app secret, and passes the signature in the `privy-authorization-signature` header.

```ts {skip-check} theme={"system"}
await fetch('https://api.privy.io/v1/wallets/insert-wallet-id/rpc', {
  method: 'POST',
  headers: {
    Authorization: `Basic ${Buffer.from('insert-app-id:insert-app-secret').toString('base64')}`,
    'privy-app-id': 'insert-app-id',
    'privy-authorization-signature': signature,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
});
```

Prompt for MFA before you submit the authorization signature. Submit it before the MFA token expires, at the end of your app's MFA cache duration. If a policy requires MFA and the signature's user key records none, Privy rejects the request with `mfa_required`. See [error codes](https://docs.privy.io/authentication/user-authentication/mfa/granular/errors.md#error-codes).
