Secure Infura project key

Details: https://docs.infura.io/infura/networks/ethereum/how-to/secure-a-project

Patterns:

  • Frontend/Mobile app:
    + Requests: 10/sec, 5000/day
    + Allowlists: Origins, Contract addresses, User agents (optional)
    + JWT required: Public (short expiration), Signed (long expiration)
  • BE service:
    + Requests: x0/sec, x000/day
    + Allowlists: Contract addresses, User agents (optional)
    + Project secret required: JWT or API secret

Secure with API key secret

https://docs.infura.io/infura/networks/ethereum/how-to/secure-a-project/project-secret

curl --user :<INFURA-API-KEY-SECRET> \
https://mainnet.infura.io/v3/<INFURA-API-KEY> \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'

There 2 ways to serve:

#1. Add basic authentication to header:

Header {
Authorization: Basic base64(':<INFURA-API-KEY-SECRET>')
}

Use custom headers and agent of web3: https://web3js.readthedocs.io/en/v1.7.4/web3.html

#2. Use credentialed URLs

https://:<INFURA-API-KEY-SECRET>@mainnet.infura.io/v3/<INFURA-API-KEY>

Secure with JWTs

https://docs.infura.io/infura/learn/json-web-token-jwt

Client uses a pair (public + private keys + registered Infura public key id ) to gen a JWT token. Infura will use the public key to verify the token.

#1. Generate JWT key: https://gist.github.com/ygotthilf/baa58da5c3dd1f69fae9

ssh-keygen -t rsa -P "" -b 4096 -m PEM -f jwtRS256.keyssh-keygen -e -m PEM -f jwtRS256.key > jwtRS256.key.pub

#2. Add public key to Infura. The key has a NAME, ID (JWT-ID), FINGERPRINT. These are used for creating and verifying JWTs.

#3. Generate JWT token:

HEADER:
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "<JWT-ID-GENERATED-BY-PUBLIC-KEY>"
}
* Where:
- Use a supported algorithm (RS256 or ES256) and declare it in the alg header field.
- Specify JWT in the typ header field.
- Include the JWT ID (NOT project API key) in the kid header field.

PAYLOAD:
{
  "exp": "1958812021",
  "aud": "infura.io"
}
* Where:
- Have an unexpired exp timestamp in the payload data. https://www.freeformatter.com/epoch-timestamp-to-date-converter.html
- Specify infura.io in the aud field.
  • VERIFY SIGNATURE: with public and private key content
  • Copy generated Encoded JWT Token put to header
Header {
Authorization: Bearer <Encoded JWT Token>
}
  • Verify with curl
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <Encoded JWT Token>" \
--data '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}' \
"https://rinkeby.infura.io/v3/<INFURA-API-KEY>"