Authentication with the Block-Auth SDK

This guide will get you all set up and ready to use the Block-Auth SDK. We'll cover how to get started using one of our SDK clients and how to make your first SDK request. We'll also look at where to go next to find all the information you need to take full advantage of our powerful REST SDK.

Choose your client

Before making your first request, you need to pick which SDK client you will use. Block-Auth offers clients for JavaScript. In the following example, you can see how to install client.

# Install the Protocol JavaScript SDK
npm install blockauth-sdk --save

Connecting using credentials

After picking your preferred client, you are ready to make your first call to the Protocol SDK. Below, you can see how to send a GET request to the Conversations endpoint to get a list of all your conversations. In the cURL example, results are limited to ten conversations, the default page length for each client.

SDK
connection
import { BlockAuthProvider } from 'blockauth-sdk'

const provider = new BlockAuthProvider({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
})
// allow your backend to connect to the block-auth provider (blockchain + api)
await provider.connect()
// allow to access to your app data with the block-auth provider
await provider.signin()

Verify USER is logged in or not into APP

We follow the standard down RFC 6750, where we use the Bearer token to authenticate the user. The user can be authenticated by the SDK using the isAddressSigned method.

SDK
connection
import { BlockAuthProvider } from 'blockauth-sdk'

const provider = new BlockAuthProvider({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
})
const userAddress = '0x1234567890'
// allow your backend to connect to the block-auth provider (blockchain + api)
await provider.connect()
// allow to access to your app data with the block-auth provider
await provider.signin()

await provider.isAddressSigned(userAddress)

Example with EXPRESS api

import express from 'express'
import { BlockAuthProvider } from 'blockauth-sdk'

const app = express()
const provider = new BlockAuthProvider({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
})
// allow your backend to connect to the block-auth provider (blockchain + api)
await provider.connect()
// allow to access to your app data with the block-auth provider
await provider.signin()

app.get('/auth/:address', async (req, res) => {
  try {
    const { address } = req.params
    const res = await provider.isAddressSigned(address)
    res.status(200).json({ ...res })
  } catch (error) {
    res.status(500).json({ success:false, error: error.message })
  }
})

app.listen(3000, () => {
  console.log('API REST running on port 3000')
})

Example with EXPRESS+JWT api


import express from 'express'
import jwt from 'jsonwebtoken'
import { BlockAuthProvider } from 'blockauth-sdk'

const secretforJWT = 'secret'
const app = express()
const provider = new BlockAuthProvider({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
})
// allow your backend to connect to the block-auth provider (blockchain + api)
await provider.connect()
// allow to access to your app data with the block-auth provider
await provider.signin()
console.log('[api][blockauth-sdk] provider READY to use for APP: ', await provider.app())
/**
 * Apply RCF6750 - bearer+1space+base64token
 *  list of users must be contain at least one user
 *  and the address must be the same as the one in the list
 * @param {*} users list of users queried from db
 * @param {*} addr address to be signed
 * @param {*} expiresIn token expiration time (from block-auth provider)
*/
const tokenCreateFromAddress = async (users, addr, expiresIn = '1h')=> {
  const errorToken = {"message":"Token not generated"};
  const _addr = addr.toLowerCase() || '';
  if(!_addr || _addr.length <= 0) throw Error(errorToken.message);
  if(users.length <= 0) throw Error(errorToken.message);
  if(users[0].addr.toLowerCase() !== _addr) throw Error(errorToken.message);

  const token = jwt.sign(
    {...users[0]},
    secretforJWT,
    { expiresIn }
  )
  return {
    accessToken: token,
    user: users[0]
  };
}
app.get('/auth/:address', async (req, res) => {
  try {
    const { address } = req.params
    console.log("[api][/auth] by address: ", address)
    const { success, message } = await provider.isAddressSigned(address) || { success: false, message: 'Address not signed' }
    const { signedAt, signedExpiredAt } = message
    const diffInMs = new Date(signedExpiredAt).getTime() - new Date(signedAt).getTime();
    const diffInSecs = Math.floor(diffInMs / 1000);
    console.log('[api]blockauth-sdk] signed user by addr+apiKey->', success, message, diffInSecs)
    if (!success) throw Error("Address not signed")
    // address signin, generate session with address
    // now front can save it at sessionstorage and use it for next requests
    session = (await tokenCreateFromAddress(users, address, diffInSecs))
    const data = {"accessToken": session.accessToken}
    res.status(200).json({ success: true, data })
  } catch (error) {
    res.status(500).json({ success:false, error: error.message })
  }
})

app.listen(3000, () => {
  console.log('API REST running on port 3000')
})

What's next?

Great, you're now set up with an SDK client and have made your first request to the SDK. Here are a few links that might be handy as you venture further into the Protocol SDK:

Was this page helpful?