Search code examples
nearprotocol

JWT authentication for near protocol in a python backend


In ethereum, JWT authentication takes place with the following process:
https://github.com/Bearle/django-web3-auth/

1) Users sign a message in metamask using accounts private key.
2) account address and the signed message are POSTed to the backend
3) The backend verifies that the signature is correct and generates a signed Json Web Token (JWT) proving that the holder is in control of the address

Near protocol uses the following code to signing:

window.near = await nearlib.connect(Object.assign({ deps: { keyStore: new nearlib.keyStores.BrowserLocalStorageKeyStore() } }, window.nearConfig));

// Needed to access wallet login
window.walletAccount = new nearlib.WalletAccount(window.near);

And this:

await this.props.wallet.requestSignIn(
      window.nearConfig.contractName,
      appTitle
    )

How to use near login for backend, especially the verification step. In python in case of web3 it uses

from web3auth.utils import recover_to_addr

if not address == recover_to_addr(token, signature):
            return None

Can I use something in python (or javascript or rust) in the near protocol? Rust example is fine as I can call the function in python through cffi.
Please provide some code.


Solution

  • NEAR Wallet does not provide JWT authentication, but overall the procedure would be the following:

    1. User signs a message with a key (e.g. after a sign in through Wallet or near-shell from terminal); near-api-js has signMessage method on Signer interface, but you can use any ed25519 implementation to sign a binary blob using the key
    2. account id and the signed message are POSTed to the backend
    3. The backend verifies that the signature is correct using any ed25519 library to check the signature correctness (again, near-api-js KeyPair has verify method), and query NEAR RPC API to confirm that the key belongs to the account id.