create account

HOW TO: Use Hive Keychain to Authenticate Users in An Application by ura-soul

View this thread on: hive.blogpeakd.comecency.com
· @ura-soul · (edited)
$123.85
HOW TO: Use Hive Keychain to Authenticate Users in An Application
***If, like me, you've needed to know how to use Hive's awesome @keychain app to authenticate visitors to your website/dApp then you probably know that the method for doing so is hard to come by! Here's a guide that tells you all you need to know.***

![image.png](https://files.peakd.com/file/peakd-hive/ura-soul/23uExFhQmuSWi8wkQDcYk4V96Hz5FPUfciQKNBvUEpmiGNdiv6UGw34jPTZgcyQFAAP8L.png)

The developer guides for Hive, as with many open source projects, are out of date and incomplete. Sadly, one of the most important requirements for building an app on Hive is woefully under-described - user authentication.

At present (2022), the [Hive Keychain](https://hive-keychain.com/) system is the simplest and most efficient way to sign in to Hive websites, but it's documentation is (unironically) cryptic at times. The biggest challenge, though, is that the mechanism that apps rely on to use Hive to prove that a user owns a particular account is seemingly not documented at all! This information is fundamental to building apps on Hive, it needs to be visible all over - even included as initial information on Hive.io and other intro websites.

I had to spend several hours researching the process I will describe below and even then I only achieved the solution due to other developers pointing me in the right direction after appealing for help in several Discord servers.

## Concept: How Does Authentication using Hive Keychain Work?
---
The design of Hive is such that every user has multiple encryption key pairs with different permissions attached to them - *'owner', 'active', 'posting' and 'memo'*. Generally, for authentication in applications we are only interested in the *posting* and *active* keys, since these confer the necessary permissions used in most apps and are sufficiently important that most users won't give them away to other people (The active key is more powerful than the posting key, so consider checking that if you want to be sure that the person accessing your app is very likely to be the true owner of the Hive account in question).

Hive Keychain allows us to access the public key part of the private/public key pairs that are attached to all Hive accounts. So if someone attempts to sign in to our app using Hive Keychain, we can grab the public key and do some useful things with it.

Essentially, we create a unique message as text and use keychain to encrypt it into a garbled set of characters using one of the private keys associated to the user's Hive account. We then securely send this string of encrypted characters, along with the original (unencoded) message, plus the public key partner of the private key that was used to do the encryption to our server.

We then use the Hive API to check that we have the correct public key for the Hive account in question. Finally, we decrypt the encrypted message using the provided public key and check that the decrypted text matches the unencrypted text that our website originally created when the user attempted to sign in.

If the two text strings are equal then we know that whoever is attempting to sign in to your site does indeed have access to the real private key for the Hive account being used. This, then, allows us to treat this person as authenticated in our app.

## Code: How To Authenticate Hive Accounts Using Hive Keychain
---
There are several steps to this process. We start out using Javascript in the browser to connect to the user's Keychain plugin.

### Check that the Keychain plugin is installed
---
The following line checks to ensure that the keychain plugin is active:

```
if(window.hive_keychain)
```

Note: You need to interact with keychain via events in the browser since the timing of it's instantiation is such that it is not initialised when the DOM is ready in the browser (there is a short time delay).

### Retrieve and check the Hive Username
---
Next, get the user's hive username somehow - typically you will add an HTML input element to your page and ask the user to type their username into it.

You should validate the username to at least ensure that it is present and not an empty string.

### Create a unique message to encode
---
Use a timestamp for the present data/time and other information to create a string of text that can be encrypted and tested for the accuracy in our process of later decrypting it on the server.

A combination of the hive username, the current page address and a timestamp is sufficient.

### Use 'requestSignBuffer' to encode the message
---
Keychain includes a function called *requestSignBuffer* which allows us to encode a message using either the *private posting* or *private active* key of a user. The following function call will trigger this process - you pass in the Hive username and also the message string to be encoded.

```
window.keychain.requestSignBuffer(hiveUsername, JSON.stringify(messageObj), 'Posting', signBufferOutput => {})
```

This function also requires a callback function (named 'serverResponse' in this example), which will run after the process completes.

Inside the callback we will send the relevant information to our server.

### Send authentication data to our server
---
We need to use standard browser javascript to send the output from the requestSignBuffer function  to our server. 

```
var xhr = new XMLHttpRequest();
xhr.open('POST', '/yourLoginUrl', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onload = function () 
{
   var serverResponse = JSON.parse(this.responseText);
   // do stuff in the webpage after server responds
};
xhr.send(JSON.stringify({ 'data': signBufferOutput }, null, 2));
}, null, 'Login to the app.');
```

### Process the authentication data on the server
---
Now we need to do several things, firstly check to see if the user exists in our app's database or list of users. Either create a new user for them if they have not signed in before, or send them to a signup page if that's what you need.

Once we have related the user to a record in our database, we can check that the data that has been output by Hive Keychain does indeed confirm that the user is who they say they are.

The server will receive the following data from the browser:

Hive username (as text).
The unencoded message (as text).
The type of Hive key that is being used (as text).
The encoded message in a variable called 'result' (as text).
The relevant public key for the Hive account.

Check that these are present, validate as you prefer.

### Confirm Public Key
---
You can use the dHive library to check the Hive blockchain to confirm that the provided public key does belong to the named Hive account by running:
```
await client.keys.getKeyReferences([publicKey]);
```
Which returns the name of the hive account to which the public key is associated. Note: the [dHive documentation for this function](https://openhive-network.github.io/dhive/classes/accountbykeyapi.html) seems to be out of date or at least incomplete. There is currently no mention of the correct syntax to use to call the 'accountByKeyAPI' class using dHive, but I managed to find it in some source code from another project on Github.

Now you have checked that the username you have been provided from the browser is the correct one for the public key that was provided.

### Verify the message
---
Now we can finally check that the encrypted message that was sent from Hive Keychain (encrypted using one of the user's private keys) can be decoded using their public key and that it matches the original text that was encrypted by Keychain. 

The following three commands from the dHive library will perform the check.

The first two instantiate the encoded message and the public key as appropriate objects from the dHive library. The third command performs the verification, whereby the encoded message is decoded using the supplied public key and is compared to the original, unencoded, text.
```
sig = dhive.Signature.fromString(encodedMsg);
key = dhive.PublicKey.fromString(publicKey);
result = key.verify(dhive.cryptoUtils.sha256(originalMsg), sig);
```
The resulting variable will be true if the verification succeed and false if not. If the result is true, then the server has successfully confirmed that whoever sent the data from a browser did indeed have the ability to encode text using the private key associated with the provided hive username. This means that we know they have access to the private keys and have therefore authenticated themselves - without needing to provide us with any private keys.

## Conclusion
---
Hive Keychain and the private/public key encryption model built into Hive allow us a nice way to authenticate accounts without any risk on the part of the Hive account owner. Being able to do this using javascript makes it simple to manage Hive user authentication and to create interesting Decentralised apps on Hive.

Thanks to @stoodkev and the rest of the Keychain team, plus supporting community developers for making this all work! 

<br/>
Wishing you well,
Ura Soul
---
<center>
[![](https://files.peakd.com/file/peakd-hive/ura-soul/EoAYLU1RRXq357b9zCw6G4EXrp3PzySH6ZdyeENVNAJra4b7qXpaXJnEvt1QoY24Q28.png)](https://hiveonboard.com?ref=ura-soul)

<sub>[Read My User Guide for Hive Here](https://peakd.com/hive/@ura-soul/hive-user-guide-learn-how-to-join-post-blogs-upload-videos-make-friends-and-get-paid-to-co-create-the-uncensored-hive-community)</sub>
</center>
<hr/>

<div>

[![Hive Alive Banner 2.png](https://files.peakd.com/file/peakd-hive/ura-soul/23xATjQuGx21ZDWqDPQvhEw1DDCJc4xL8oxFVNZx2V5rVLdk5qzuPFxJ1uCHnjZ7GiqwY.png)](https://hivealive.io)
<sub>Powerful insights into the Hive blockchain are available at my website, [Hive Alive](https://hivealive.io).<br/>Including the only way to track downvotes on Hive - [The Untrending report](https://hivealive.io/untrending)</sub>
---
</div>


<div class="pull-left">
 <a href="http://nftsymposium.io"><img src="https://images.hive.blog/p/YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQF31nXVgNNkFnPCbVpxaAaACxi4CHsuwGoC2r6au11RLWqUTUCABqVmccPSTTSHQDFCFX2mYh2xNsYbWxfmCYok24fuwQT346wKWYaRWbGXgHBf8rjEa8e?format=match&mode=fit" alt="The NFT Symposium"/></a>
</div>

<div class="pull-right">
<sub>The NFT Symposium is a community space where NFT creators, artists, traders, enthusiasts & visionaries rub virtual shoulders, share ideas, start projects, grow together & learn.
<br/><br/>
Get paid to mine your imagination for the benefit of the entire NFT world:</sub>
<br/>
<sub><a href="http://nftsymposium.io">NFTSymposium.io</a>.</sub>
</div>

---

<div class="pull-left">
<div class="text-center">

[![](https://files.peakd.com/file/peakd-hive/ura-soul/2j3zxDZW-ura20soul20witness20vote20for20hive.png)](https://hivesigner.com/sign/account-witness-vote?witness=ura-soul&approve=1)
<div class="text-center">
<a href="https://peakd.com/witness-category/@ura-soul/vote-ura-soul-as-your-hive-witness">View My Witness Application Here</a>
<br/>
<sub><a href="https://peakd.com/@ura-soul?filter=urasoul-witness">View Some of My Witness Related Posts</a></sub><br/><br/></div>
</div></div>
<div class="pull-right">
<a href="https://www.crucialweb.co.uk">
<img src="https://uploads-ssl.webflow.com/5dcaa59d375b7c29913ac61e/60e31a4a1bfb87398d52a90e_crucial-web-internet-marketing.png" alt="Crucial Web, digital marketing agency in Norwich, UK"/></a>
<div><sub>
Looking for ethical <a href="https://www.crucialweb.co.uk">Digital Marketing Agency</a>?<br/>
@crucialweb can help you to grow and innovate online.</sub>
</div>
</div>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 389 others
👎  , , , , ,
properties (23)
authorura-soul
permlinkhow-to-use-hive-keychain-to-authenticate-users-in-an-application
categoryhive-139531
json_metadata{"app":"peakd/2022.10.3","format":"markdown","tags":["hive","development","developer","dapp","howto","help","coding","keychain","authentication","hivekeychain"],"users":["keychain","stoodkev","ura-soul","crucialweb"],"image":["https://files.peakd.com/file/peakd-hive/ura-soul/23uExFhQmuSWi8wkQDcYk4V96Hz5FPUfciQKNBvUEpmiGNdiv6UGw34jPTZgcyQFAAP8L.png","https://files.peakd.com/file/peakd-hive/ura-soul/EoAYLU1RRXq357b9zCw6G4EXrp3PzySH6ZdyeENVNAJra4b7qXpaXJnEvt1QoY24Q28.png","https://files.peakd.com/file/peakd-hive/ura-soul/23xATjQuGx21ZDWqDPQvhEw1DDCJc4xL8oxFVNZx2V5rVLdk5qzuPFxJ1uCHnjZ7GiqwY.png","https://images.hive.blog/p/YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQF31nXVgNNkFnPCbVpxaAaACxi4CHsuwGoC2r6au11RLWqUTUCABqVmccPSTTSHQDFCFX2mYh2xNsYbWxfmCYok24fuwQT346wKWYaRWbGXgHBf8rjEa8e?format=match&amp;mode=fit","https://files.peakd.com/file/peakd-hive/ura-soul/2j3zxDZW-ura20soul20witness20vote20for20hive.png","https://uploads-ssl.webflow.com/5dcaa59d375b7c29913ac61e/60e31a4a1bfb87398d52a90e_crucial-web-internet-marketing.png"]}
created2022-11-03 19:54:54
last_update2022-11-05 14:19:21
depth0
children13
last_payout2022-11-10 19:54:54
cashout_time1969-12-31 23:59:59
total_payout_value61.968 HBD
curator_payout_value61.879 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11,566
author_reputation771,016,129,970,476
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,036,913
net_rshares237,324,450,775,287
author_curate_reward""
vote details (459)
@amr008 ·
$0.08
Is there any way I can interact with the HiveKeychain through Python API? :( 
👍  
properties (23)
authoramr008
permlinkre-ura-soul-rkt7od
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 06:07:27
last_update2022-11-04 06:07:27
depth1
children3
last_payout2022-11-11 06:07:27
cashout_time1969-12-31 23:59:59
total_payout_value0.040 HBD
curator_payout_value0.041 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length77
author_reputation61,403,929,105,681
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,047,583
net_rshares177,059,567,269
author_curate_reward""
vote details (1)
@ura-soul ·
Keychain operates in browsers, which themselves run javascript - so you can't get around using Javascript in the browser.

I don't use Python myself but I imagine you would be able to run Python on your server to process the server side component of the process described here. There are [tutorials for Python on the Hive developer website](https://developers.hive.io/tutorials/#tutorials-python), but you might need to dig around to find the correct functions to use for the keychain authentication process. 

The library 'Beem' is promoted for Python with Hive but I think that the author, @holger80, no longer maintains it. I can see [a few functions in Beem](https://beem.readthedocs.io/en/latest/cli.html?highlight=verify#beempy-message) that might do what you need, but I have no experience with it - I imagine if you ask in the Hive developer Discord area you will get the answers you need.
properties (22)
authorura-soul
permlinkre-amr008-rktqqs
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 12:59:15
last_update2022-11-04 12:59:15
depth2
children2
last_payout2022-11-11 12:59:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length897
author_reputation771,016,129,970,476
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,055,218
net_rshares0
@amr008 ·
$0.08
Oh yeah I am fully aware of Beem and Hive-engine libraries . In fact I had my own site up ad running but only part where I struggled was connecting to Keychain . 

Thanks for the reply :)
👍  
properties (23)
authoramr008
permlinkre-ura-soul-rkv4pb
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-05 06:58:21
last_update2022-11-05 06:58:21
depth3
children1
last_payout2022-11-12 06:58:21
cashout_time1969-12-31 23:59:59
total_payout_value0.038 HBD
curator_payout_value0.039 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length187
author_reputation61,403,929,105,681
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,076,879
net_rshares178,841,325,527
author_curate_reward""
vote details (1)
@doabit ·
$0.08
Thank you for this information. Btw some kind of GitHub example code would 
be  appreciated as much more useful than a long text description. :)
👍  
properties (23)
authordoabit
permlinkre-ura-soul-rkt7l7
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 06:05:33
last_update2022-11-04 06:05:33
depth1
children4
last_payout2022-11-11 06:05:33
cashout_time1969-12-31 23:59:59
total_payout_value0.041 HBD
curator_payout_value0.041 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length144
author_reputation2,515,360,580,046
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,047,554
net_rshares180,505,653,816
author_curate_reward""
vote details (1)
@ura-soul ·
You are welcome. I aim to stay away from relying on corporate products where possible - Github is now a Microsoft product, whereas Hive is public.
properties (22)
authorura-soul
permlinkre-doabit-rktqg2
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 12:52:51
last_update2022-11-04 12:52:51
depth2
children3
last_payout2022-11-11 12:52:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length146
author_reputation771,016,129,970,476
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,055,078
net_rshares0
@doabit ·
$0.08
Sure. Then maybe here in "'''" or whatever is markdown for code. Just having it in one file with comment ("//") in a "file" would make it much easier and faster to read for tech people. Still great source thanks again.
👍  
properties (23)
authordoabit
permlinkre-ura-soul-rktypp
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 15:51:27
last_update2022-11-04 15:51:27
depth3
children2
last_payout2022-11-11 15:51:27
cashout_time1969-12-31 23:59:59
total_payout_value0.040 HBD
curator_payout_value0.040 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length218
author_reputation2,515,360,580,046
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,059,478
net_rshares176,042,629,934
author_curate_reward""
vote details (1)
@lady-tee ·
$0.08
this is a huge work, thanks so much for taking out such time to educate me as a person, learning so much already 
👍  
properties (23)
authorlady-tee
permlinkre-ura-soul-20221110t83845814z
categoryhive-139531
json_metadata{"tags":["hive","development","developer","dapp","howto","help","coding","keychain","authentication","hivekeychain"],"app":"ecency/3.0.28-vision","format":"markdown+html"}
created2022-11-10 07:38:45
last_update2022-11-10 07:38:45
depth1
children0
last_payout2022-11-17 07:38:45
cashout_time1969-12-31 23:59:59
total_payout_value0.039 HBD
curator_payout_value0.039 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length113
author_reputation1,307,581,204,095
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,215,960
net_rshares186,693,053,254
author_curate_reward""
vote details (1)
@poshtoken ·
https://twitter.com/1577585531395145729/status/1590155826777706496
<sub> The rewards earned on this comment will go directly to the people( @keychain ) sharing the post on Twitter as long as they are registered with @poshtoken. Sign up at https://hiveposh.com.</sub>
properties (22)
authorposhtoken
permlinkre-ura-soul-how-to-use-hive-keychain-to-authenticate-users-in--1675
categoryhive-139531
json_metadata"{"app":"Poshtoken 0.0.1","payoutToUser":["keychain"]}"
created2022-11-09 01:37:30
last_update2022-11-09 01:37:30
depth1
children0
last_payout2022-11-16 01:37:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length267
author_reputation3,943,443,221,588,481
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries
0.
accountreward.app
weight10,000
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id118,182,763
net_rshares0
@wisdomterritory ·
$0.09
Thank you very much for this wonderful info..
👍  
properties (23)
authorwisdomterritory
permlinkre-ura-soul-2022113t221737619z
categoryhive-139531
json_metadata{"tags":["hive","development","developer","dapp","howto","help","coding","keychain","authentication","hivekeychain"],"app":"ecency/3.0.28-vision","format":"markdown+html"}
created2022-11-03 21:17:39
last_update2022-11-03 21:17:39
depth1
children1
last_payout2022-11-10 21:17:39
cashout_time1969-12-31 23:59:59
total_payout_value0.046 HBD
curator_payout_value0.047 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length45
author_reputation-266,698,612,156
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,038,712
net_rshares184,165,660,798
author_curate_reward""
vote details (1)
@ura-soul ·
You are welcome.
properties (22)
authorura-soul
permlinkre-wisdomterritory-rktqeh
categoryhive-139531
json_metadata{"tags":["hive-139531"],"app":"peakd/2022.10.3"}
created2022-11-04 12:51:54
last_update2022-11-04 12:51:54
depth2
children0
last_payout2022-11-11 12:51:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length16
author_reputation771,016,129,970,476
root_title"HOW TO: Use Hive Keychain to Authenticate Users in An Application"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id118,055,048
net_rshares0