Integrating HAS (Hive Authentication Services) on your website

in HiveDevs2 years ago (edited)

The Hive Authentication Services provide a way for any applications, (either web, desktop or mobile) to easily authenticate users without asking them to provide any password or private key.
Source: https://docs.hiveauth.com/

In the following paragraphs I will be describing the process on how to integrate HAS on your website.
The first step is to install the required npm package by running

npm install hive-auth-wrapper --save

Then you may test out the HAS connection by importing the HAS object and checking the status

import HAS from 'hive-auth-wrapper'

const status = HAS.status()
console.log(status)

which should print something like

{host: 'wss://hive-auth.arcange.eu/', connected: false, timeout: 60000}

Next you need to define a metadata object for identifying your application upon an authentication requests:

  const APP_META = {
    name: "name of the app",
    description: "description of the app",
    icon: "url pointing to app logo",
  };

Create a login dialog with an input field for the username:

and after the click on login set it on an auth object

const auth = {
    username: username,
    token: undefined,
    expire: undefined,
    key: undefined,
};

and send the authentication request to HAS with an optional challenge_data object:

const challenge_data = {
  key_type: 'posting',
  challenge: JSON.stringify({
    login: auth.username,
    ts: Date.now(),
  })
}
HAS.authenticate(auth, APP_META, challenge_data, (evt) => {
      // process the auth_wait event
  }))
  .then(res => {
    // the authentication request was successful
  })
  .catch(err => {
    // the authentication request expired, was canceled or an error occurred
  });

In case the user is not authenticated yet an auth_wait event will occur, which needs to be handled by generating a HAS authentication request url. This is done by first creating an authentication payload object, encoding it in base64 and creating an url from that:

const authPayload = {
  account: username,
  uuid: evt.uuid,
  key: evt.key,
  host: status.host,
};
const encoded = btoa(JSON.stringify(authPayload));
const url = `has://auth_req/${encoded}`;

The url is then best shown to the user in form of a QR code:

Now the user needs to open e.g. Hive Keychain, scan the QR code and approve the request. After 60 seconds the request will expire and if the user cancels the request a auth_nack event will be fired.

In case the user successfully signs the request a auth_ack will occur, which means the user was successfully signed in and the token, expire and key will be updated in the auth object accordingly.
If we want to restore the session when the user next visits the site we need to store the auth object e.g. in local storage. We can restore the session by loading the auth object and simply checking:

if(auth?.token && auth?.expire > Date.now()) {
  // session is still valid and user can be signed in
} else {
  // session has expired and user needs to sign in again
}

If you want to broadcast a transaction for the logged in user you can use the auth object and an op array containing the actual operation

HAS.broadcast(auth, "posting", [op], (evt)=> {
    // process sign_wait message
}) )
.then(res => {
  // transaction approved and broadcasted
} )
.catch(err => {
  // transaction failed or rejected
} );

and handle the response in case of success or failure accordingly.

I am almost done with integrating HAS into my monitor site, but more on that once the process is completed.

Thanks @arcange et al. for this awesome new service and thank you for your great presentation(s) at HiveFest, which motivated me to integrate this into my site. Unfortunately I could only watch the live stream, but hopefully next year I will make it there in person :)

If you found this useful and need more details / help integrating this into your site please let me know or check out the official docs, which are also very useful https://docs.hiveauth.com.

Please consider voting me as HIVE witness, so I can build more awesome stuff.

Sort:  

What is the meaning of HAS and to be honest am not too clear on this maybe I should read through again and see if I would get something out of it thanks for sharing this tutorial.

HAS is basically a "middleman" between apps and wallets. So if you want to sign in to an app using your hive account, HAS provides the method for authenticating without giving the app your private keys. This would allow basically any website (even outside of Hive) to implement an authentication using Hive accounts. I think this image (taken from https://docs.hiveauth.com) describes it quite good. A website requests a login or broadcast of a transaction and HAS communicates with your preferred wallet application to sign the transaction:

Thanks for explaining.

This is the type of content that I appreciate the most. I'm not developing a project on Hive yet, but I added this post to my bookmarks for some day in the future when it could be very helpful. Thanks!

Thank you. I think a large part of the process could still be optimized or made easier for frontend devs by creating another wrapper library e.g. for Angular to even speed up the process of integrating HAS into websites.

I completely agree. Integrating both Keychain and HAS login options makes it more difficult too as it seems to require different code for things like broadcasting transactions depending on the login method that was used.

Yeah that's what I noticed too, a lib would be definitely great, but probably hard to maintain as specs and dependencies tend to change fast. I will have a look into it, as basically I already got most of the code for broadcasting using Keychain, Hivesigner and HAS in my app.

In which app did you integrate HiveAuth?

I didn't integrate it fully yet, there are still a few things I need to do first, like storing / restoring sessions if they didn't expire yet, broadcasting of transactions and a few UI related things. But after I finished that it will go live on https://primersion.com for broadcasting witness vote transactions through HiveAuth. I will be explaining details in an updated post once it goes live.
Additionally I am currently developing another app, which will include it as well, but I am not sure when this one will be released.

Thanks! This post was very helpful combined with the HTML example here: https://github.com/hiveauth/hive-auth-html. The HTML example shows how to listen for auth_ack events and generate QR images.

Yay! 🤗
Your content has been boosted with Ecency Points, by @primersion.
Use Ecency daily to boost your growth on platform!

Support Ecency
Vote for new Proposal
Delegate HP and earn more

Hey dear @ecency team,

would it be possible to integrate HiveAuth or HAS into your service??

I would love it! Means I can use it more on my mobile....

It is in our backlog, until then you can try Ecency mobile apps.
https://ios.ecency.com
https://android.ecency.com

yeah love to do.
But can't use it as I don't want to enter any of my keys direct into an App. or HiveSigner.

Your frontend is so lovely and powerful, let's make is safe as well.

It is safe, as safest as it can get, anyone claiming otherwise do point us our way so we can elaborate more and explain. You can double encrypt your keys with PIN + fingerprint/Face ID. Hivesigner is also same structure as keychain in terms of where and how keys are stored. Both website and mobile apps of Ecency is opensource you can check GitHub.com/Ecency.

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.