B4J Code Snippet Web3X - Login/Auth with Metamask example

I've been using the Web3X library these past days and wonder how could it be used for authentication with Metamask. I put together this example but is not near perfect, I don't recommend using it in production since there are a lot of things I don't understand yet, but if your goal is to learn you could run this code.

I took ideas from many sites to understand what should be done, mainly the web3js docs: https://web3js.readthedocs.io/en/v1.5.2/

The code flow looks like this (source):

You must run the b4j server and access it by localhost, otherwise the Metamask wallet will not be detected if you just open the index.html.

The index.html file is just a button on the top left corner of the screen. When pressed we try to connect to the wallet, then get a random message from the server, sign the message and return it for verification, if passed, we get a token which will allow for fast authentication.

The attached screenshots show the process from start to finish.

Disclaimer: After reading the permissions the Metamask chrome extension requires, I don't known how safe it is. For transparency, I created a VM running ubuntu just to play around with crypto apps, I do not run them on my main computer.


  • 1.png
    96.4 KB · Views: 315
  • 2.png
    135.1 KB · Views: 329
  • 3.png
    137.4 KB · Views: 306
  • 4.png
    132.1 KB · Views: 297
  • 5.png
    111.5 KB · Views: 317
  • web3j-metamask-demo.zip
    23.8 KB · Views: 201