create account

How to Use Steem Keychain Login in Your Node JS Website/API by reazuliqbal

View this thread on: hive.blogpeakd.comecency.com
· @reazuliqbal ·
$26.68
How to Use Steem Keychain Login in Your Node JS Website/API
<center>![cover.png](https://cdn.steemitimages.com/DQmPvyqKkwDwvrGbdRbVmUWSHm9Y87xUyK2511daePko6iE/cover.png)</center>

Steem Keychain is a Steem wallet plugin for browsers that enables users to securely store your private keys and sign transactions using their key(s) securely.

At 2020 Steem Keychain should be the preferred way to log into any Steem dApps. In this post, I am going to write about how can we implement Steem Keychain authentication (also authorization) into our Node JS website or API.

## Goal

Our goal is to verify a user is a user they are claimed to be. So, we are going to verify by having them sign a predefined message using any of their private keys ( Posting, Active, Memo) and later trying to decode the signed message using their public key (Posting, Active, Memo - whichever was used to sign). If we can recover the original message, this validates that the user has to access/owns the account. So, they are authenticated. Now we can issue them a token (JSON Web Tokens) signed by us to authorize the use of our website/API.

## Client

We need a predefined message preferably unique for each user. We will ask our users to sign the message using their Posting key. After signing we are going to send a POST request with the `username`, `message`, and `signed message` to our API login endpoint `/users/login`. `API.post` is an interface to send HTTP request using [axios](https://github.com/axios/axios). If successful our server would respond with a JWT token which we can use to access/modify data.

<center>![screenshot-01.png](https://cdn.steemitimages.com/DQmeANSwRnNmHCeS5NFZwmVHAT2JF8tvqparrzqGkfRd1gx/screenshot-01.png)</center>
<center><sup>Users will get a popup like this to sign the message.</sup></center>


Here is how the code might look like.

```javascript=
const message = Date.now(); // Generating the message

window.steem_keychain.requestSignBuffer('username', message, 'Posting', async (r) => {
    if (r.success) {
        // User has signed the message
        try {
            // We are sending HTTP POST request to our API login endpoint
            // with the username, message, and the signed message
            const { token } = await API.post('users/login', {
              username,
              message,
              signed_message: r.result,
            });
            
            // Saving the token into localStorage for later use
            localStorage.setItem('token', token);
            
            // More codes to use the received token
        } catch(e) {
            console.log(e);
        }
    }
});

```

## Server

We have seen how to ask users to sign and send the signed message to our login endpoint. Now let's see how the login endpoint might look like. I am going to assume we are using Express JS for our backend server.

First, we pick `username`, `message`, and `signed message` from the POST request's body. Then we are going to fetch the users Publick posting key from the chain. After that, we are going to recover the public key from the signed message and match it against the public key pulled from the chain.

If both match, we can safely assume the user is who they are claimed to be. We are going to issue them a JTW token which they can use to interact with our website/API.

```javascript=

const jwt = require('jsonwebtoken');
const { Router } = require('express');
const { Client, Signature, cryptoUtils } = require('dsteem');

const steemClient = new Client('https://api.steemit.com');
const router = new Router();

router.post('users/login', async (req, res) => {
    try {
        // Picking username, message, and signed messsage
        // from the request body
        const { username, message, signed_message: signedMessage} = req.body;

        // Fetching account info from the chain
        const [account] = await steemClient.database.getAccounts([username]);

        const pubPostingKey = account.posting.key_auths[0][0];

        // Recovering public key from the signed message
        const recoveredPubKey = Signature.fromString(signedMessage)
            .recover(cryptoUtils.sha256(message));

        if (pubPostingKey === recoveredPubKey.toString()) {
            // Public key matched.
            // We have verified the user has access to the account.

            // let's issue them a JTW token

            const token = jwt.sign({
              sub: username,
              // Any other data you may need
            }, process.env.JWT_SECRET, { expiresIn: '12h'});

            // Responding with the generated token
            return res.json({ token });
        }
    } catch(e) {
        console.log(e);
    }
    
    return res.json({ error: 'Invalid login details.' });
});
```

In the example above we are issuing only one token (access key), we can extend it to issue two or more tokens (refresh key) too. Also, make other endpoints to support full OAuth2 authentication flow. You can also extend it by generating the message on the server and saving them into the database along with the session to allow/control multiple sessions and enable users to end a session as we see on Facebook and Google.

Please let me know if you have any suggestions in the comments below.

I am not claiming this is the best way to authenticate users using Steem Keychain. Please use it at your own risk and test the codes in your projects. I can not be held responsible for any loss might happen as a result of using these codes.

<center>[![MM.png](https://cdn.steemitimages.com/DQmQ5kU9gqfkWNA5fqBMcTEaQ7u1XGmDjuPRhTDh9KEy4TZ/MM.png)](https://monstermarket.io/?ref=reazuliqbal)</center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 116 others
👎  , , , ,
properties (23)
authorreazuliqbal
permlinkhow-to-use-steem-keychain-login-in-your-node-js-website-api
categorysteemdev
json_metadata{"tags":["steemdev","steem","keychain","nodejs","expressjs","api","neoxian","palnet"],"image":["https://cdn.steemitimages.com/DQmPvyqKkwDwvrGbdRbVmUWSHm9Y87xUyK2511daePko6iE/cover.png","https://cdn.steemitimages.com/DQmeANSwRnNmHCeS5NFZwmVHAT2JF8tvqparrzqGkfRd1gx/screenshot-01.png","https://cdn.steemitimages.com/DQmQ5kU9gqfkWNA5fqBMcTEaQ7u1XGmDjuPRhTDh9KEy4TZ/MM.png"],"links":["https://github.com/axios/axios","https://monstermarket.io/?ref=reazuliqbal"],"app":"steemit/0.1","format":"markdown"}
created2020-01-21 13:32:09
last_update2020-01-21 13:32:09
depth0
children15
last_payout2020-01-28 13:32:09
cashout_time1969-12-31 23:59:59
total_payout_value13.458 HBD
curator_payout_value13.223 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length5,623
author_reputation61,984,354,446,410
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id94,608,685
net_rshares89,510,074,879,163
author_curate_reward""
vote details (185)
@bdvoter.cur ·
You post has been manually curated by BDvoter Team! To know more about us please visit our [website](https://bdvoter.com/) or join our [Discord](https://discord.gg/yEPcKTq).

<sup>BDvoter Team</sup>
properties (22)
authorbdvoter.cur
permlinkk5nxacmt
categorysteemdev
json_metadata{"app":"bdcommnunity/1.0.0"}
created2020-01-21 13:37:06
last_update2020-01-21 13:37:06
depth1
children0
last_payout2020-01-28 13:37:06
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_length199
author_reputation447,482,224,653,577
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,608,837
net_rshares0
@contrabourdon ·
!steem2email
properties (22)
authorcontrabourdon
permlinkre-reazuliqbal-q4glnq
categorysteemdev
json_metadata{"tags":["steemdev"],"app":"steempeak/2.2.8"}
created2020-01-21 13:33:27
last_update2020-01-21 13:33:27
depth1
children1
last_payout2020-01-28 13:33:27
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_length12
author_reputation224,090,063,724,242
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,608,725
net_rshares0
@steem2email ·
Emailed &#128076;
<hr>Powered by witness <a href="https://untersatz.steem.design">untersatz</a>!
properties (22)
authorsteem2email
permlinkgtmon47uzga
categorysteemdev
json_metadata""
created2020-01-21 13:33:39
last_update2020-01-21 13:33:39
depth2
children0
last_payout2020-01-28 13:33:39
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_length96
author_reputation112,313,680
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,608,730
net_rshares0
@keys-defender ·
$0.05
Update:
https://github.com/hive-keychain/hive-keychain-extension/blob/master/documentation/README.md#requestsignbuffer
👍  
properties (23)
authorkeys-defender
permlinkre-reazuliqbal-rgfxjc
categorysteemdev
json_metadata{"tags":["steemdev"],"app":"peakd/2022.07.1"}
created2022-08-11 07:45:18
last_update2022-08-11 07:45:18
depth1
children0
last_payout2022-08-18 07:45:18
cashout_time1969-12-31 23:59:59
total_payout_value0.024 HBD
curator_payout_value0.024 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length118
author_reputation91,064,336,617,876
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id115,624,442
net_rshares67,056,045,775
author_curate_reward""
vote details (1)
@mys ·
$0.03
Brilliant. I am trying to do same thing in Python.
👍  
properties (23)
authormys
permlinkre-reazuliqbal-q4i21a
categorysteemdev
json_metadata{"tags":["steemdev"],"app":"steempeak/2.2.8"}
created2020-01-22 08:24:48
last_update2020-01-22 08:24:48
depth1
children3
last_payout2020-01-29 08:24:48
cashout_time1969-12-31 23:59:59
total_payout_value0.014 HBD
curator_payout_value0.014 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length50
author_reputation14,948,575,541,320
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,633,415
net_rshares185,950,674,958
author_curate_reward""
vote details (1)
@reazuliqbal ·
Great. @anthonyadavisii might be very interested in that. He is trying the same too.
👍  ,
properties (23)
authorreazuliqbal
permlinkq4icoi
categorysteemdev
json_metadata{"users":["anthonyadavisii"],"app":"steemit/0.1"}
created2020-01-22 12:14:42
last_update2020-01-22 12:14:42
depth2
children2
last_payout2020-01-29 12:14:42
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_length84
author_reputation61,984,354,446,410
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id94,642,507
net_rshares54,898,722,238
author_curate_reward""
vote details (2)
@mys ·
$0.03
I ended up going different way.
Server encode a token/secret using user's public key. Then user decode it using `steem_keychain.requestVerifyKey`. If successful then we got a handshake for the future.
👍  , ,
properties (23)
authormys
permlinkre-reazuliqbal-q4jzmm
categorysteemdev
json_metadata{"tags":["steemdev"],"app":"steempeak/2.2.8"}
created2020-01-23 09:28:00
last_update2020-01-23 09:28:00
depth3
children1
last_payout2020-01-30 09:28:00
cashout_time1969-12-31 23:59:59
total_payout_value0.016 HBD
curator_payout_value0.015 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length200
author_reputation14,948,575,541,320
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,678,463
net_rshares204,684,225,940
author_curate_reward""
vote details (3)
@shoemanchu ·
Wish I stayed in the computer world years ago and learned how to code and more. I guess its never to late but I just got so many things going on. Great post....
properties (22)
authorshoemanchu
permlinkq4hfsp
categorysteemdev
json_metadata{"app":"steemit/0.1"}
created2020-01-22 00:24:21
last_update2020-01-22 00:24:21
depth1
children1
last_payout2020-01-29 00:24:21
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_length160
author_reputation399,048,645,875,005
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,625,032
net_rshares0
@reazuliqbal ·
Thanks man. Yeah 100%, its never too late. Hard thing is to start as we all have many things going on.....
👍  ,
properties (23)
authorreazuliqbal
permlinkq4hly3
categorysteemdev
json_metadata{"app":"steemit/0.1"}
created2020-01-22 02:37:21
last_update2020-01-22 02:37:21
depth2
children0
last_payout2020-01-29 02:37:21
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_length106
author_reputation61,984,354,446,410
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id94,627,297
net_rshares54,898,722,238
author_curate_reward""
vote details (2)
@steemitboard ·
Congratulations @reazuliqbal! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@reazuliqbal/community.png</td><td>Thank you for the witness votes you made to support your Steem community and for keeping the Steem blockchain decentralized</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@reazuliqbal) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=reazuliqbal)_</sub>


**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmTugCUsoXX762vg1CuHRrpnPbfnjPogp8iCGv7F2kSVuj/image.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge">Use your witness votes and get the Community Badge</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-reazuliqbal-20200306t021147000z
categorysteemdev
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2020-03-06 02:11:48
last_update2020-03-06 02:11:48
depth1
children0
last_payout2020-03-13 02:11:48
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_length1,193
author_reputation38,975,615,169,260
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,104,448
net_rshares0
@steemitboard ·
Congratulations @reazuliqbal! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@reazuliqbal/downvote_js.png</td><td>Look's like you do not like Justin. Did you really downvote him?</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@reazuliqbal) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=reazuliqbal)_</sub>


**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmTugCUsoXX762vg1CuHRrpnPbfnjPogp8iCGv7F2kSVuj/image.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge">Use your witness votes and get the Community Badge</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-reazuliqbal-20200306t225857000z
categorysteemdev
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2020-03-06 22:58:57
last_update2020-03-06 22:58:57
depth1
children0
last_payout2020-03-13 22:58:57
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_length1,136
author_reputation38,975,615,169,260
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,131,935
net_rshares0
@steemitboard ·
Congratulations @reazuliqbal! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@reazuliqbal/downvote_stinc.png</td><td>Did you downvote Steemit's posts because its owner converted it into a sockpuppets factory? OK, you deserve that badge!</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@reazuliqbal) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=reazuliqbal)_</sub>


**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmTugCUsoXX762vg1CuHRrpnPbfnjPogp8iCGv7F2kSVuj/image.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge">Use your witness votes and get the Community Badge</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-reazuliqbal-20200307t004345000z
categorysteemdev
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2020-03-07 00:43:45
last_update2020-03-07 00:43:45
depth1
children0
last_payout2020-03-14 00:43:45
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_length1,194
author_reputation38,975,615,169,260
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,134,045
net_rshares0
@steemitboard ·
Congratulations @reazuliqbal! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@reazuliqbal/downvote_ned.png</td><td>Ned is definitly not your friend anymore. Did you really downvote him?</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@reazuliqbal) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=reazuliqbal)_</sub>


**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/downvote-challenge-add-up-to-3-funny-badges-to-your-board"><img src="https://steemitimages.com/64x128/https://steemitimages.com/0x0/![](https://cdn.steemitimages.com/DQmUuJkZdnSpHVWssxF82ntymqXg4Pvk6K6bYvckUYVRsnj/image.png)"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/downvote-challenge-add-up-to-3-funny-badges-to-your-board">Downvote challenge - Add up to 3 funny badges to your board</a></td></tr><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmTugCUsoXX762vg1CuHRrpnPbfnjPogp8iCGv7F2kSVuj/image.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/use-your-witness-votes-and-get-the-community-badge">Use your witness votes and get the Community Badge</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-reazuliqbal-20200307t111248000z
categorysteemdev
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2020-03-07 11:12:48
last_update2020-03-07 11:12:48
depth1
children0
last_payout2020-03-14 11:12:48
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_length1,634
author_reputation38,975,615,169,260
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,143,656
net_rshares0
@tts ·
To listen to the audio version of this article click on the play image.
[![](https://s18.postimg.org/51o0kpijd/play200x46.png)](http://ec2-52-72-169-104.compute-1.amazonaws.com/reazuliqbal__how-to-use-steem-keychain-login-in-your-node-js-website-api.mp3)
Brought to you by [@tts](https://steemit.com/tts/@tts/introduction). If you find it useful please consider upvoting this reply.
👎  ,
properties (23)
authortts
permlinkre-how-to-use-steem-keychain-login-in-your-node-js-website-api-20200121t134125
categorysteemdev
json_metadata""
created2020-01-21 13:41:27
last_update2020-01-21 13:41:27
depth1
children0
last_payout2020-01-28 13:41:27
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_length382
author_reputation-4,535,154,553,995
root_title"How to Use Steem Keychain Login in Your Node JS Website/API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id94,608,951
net_rshares-26,026,153,309
author_curate_reward""
vote details (2)