Ethers.js

連接到啟用 JWT 的網路時,如何在 JsonRpcProvider url 標頭中添加 JWT 令牌?

  • April 21, 2021

當連接到啟用JWT 公鑰認證的 Besu 網路時,如何將令牌添加到JsonRpcProvider (ethers 5.0.8)?這是目前程式碼(在添加 JWT 令牌之前):

let provider_url = "http://node-ip:80"   
const provider = new ethers.providers.JsonRpcProvider(provider_url);
let wallet = new ethers.Wallet(privateKey, provider);  //<<==generate wallet for the provider above

根據上面的 Besu 文件,可以在 Bearer 之後的 header 中添加 JWT 令牌:

curl -X POST -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJwZXJtaXNzaW9ucyI6WyIqOioiXSwidXNlcm5hbWUiOiJ1c2VyMiIsImlhdCI6MTU1MDQ2MTQxNiwiZXhwIjoxNTUwNDYxNzE2fQ.WQ1mqpqzRLHaoL8gOSEZPvnRs_qf6j__7A3Sg8vf9RKvWdNTww_vRJF1gjcVy-FFh96AchVnQyXVx0aNUz9O0txt8VN3jqABVWbGMfSk2T_CFdSw5aDjuriCsves9BQpP70Vhj-tseaudg-XU5hCokX0tChbAqd9fB2138zYm5M' -d '{"jsonrpc":"2.0","method":"net_listening","params":[],"id":1}' http://localhost:8545

StaticJsonRpcProvider需要連接到啟用 JWT 的 Besu 網路。這是工作程式碼:

connection.url = GLOBAL.PROVIDER_URL;  //url for besu rpc node
connection.headers = {
  "Authorization" : `Bearer ${ tokenBesu }`  //<<==tokenBesu is the JWT token for authorization
         };
const provider = new ethers.providers.StaticJsonRpcProvider(connection, 2018);  //2018 is network/chain ID

引用自:https://ethereum.stackexchange.com/questions/96627