Generating an authentication token

You should first use the private key you were given to generate a token authenticating the user. This must be done on a backend server. Since the private keys cannot be exposed to end users, this cannot be done on a web client.

To generate a token, use the following Python snippet (or it’s equivalent in another language):

import hashlib
import hmac
import time

# The amount of time that a token is valid is
# configurable by you. Just set the number of
# seconds this token should be valid here. We
# recommend a period between 3 and 24 hours.
VALID_DURATION_SECONDS = 24 * 60 * 60

def get_token(user_id, private_key):
    epoch = int(time.time()) + VALID_DURATION_SECONDS
    message = user_id + str(epoch)
    signature = hmac.new(
        private_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

    return {
        'user_id': user_id,
        'epoch': epoch,
        'signature': signature
    }

Tokens are valid for 24 hours. After this time, a new token must be generated.

Authenticating the user on the frontend (Web)

Every time the user is identified on the frontend, you must also pass in the token object that was generated above as part of the metadata. Simply call the following function with your signature and epoch.

// ...
// Set the user id
window.duet.setUserId(userId)
// Set the user authentication information
window.duet.setUserIdAuth(signature, epoch)

Authenticating the user on the frontend (Mobile)

For mobile, you can use a similar approach and include your signature and epoch in the request headers for your WebView. Set your signature as the X-DECAGON-AUTH-SIGNATURE header, and set your epoch as the X-DECAGON-AUTH-EPOCH header.

For example, in Swift, you can accomplish this with:

// Create and configure the URLRequest
let url = URL(string: "https://decagon.ai/mobile/<your company>")!
var request = URLRequest(url: url)
// Add your headers here
request.addValue("<your_signature>", forHTTPHeaderField: "X-DECAGON-AUTH-SIGNATURE")
request.addValue("<your_epoch>", forHTTPHeaderField: "X-DECAGON-AUTH-EPOCH")
// Use the modified WebView that accepts a URLRequest
WebView(request: request)

In React Native, you can do the same:

<WebView
  source={{
    uri: "https://decagon.ai/mobile/<your company>",
    headers: {
      "X-DECAGON-AUTH-SIGNATURE": "<your_signature>",
      "X-DECAGON-AUTH-EPOCH": "<your_epoch>"
    }
  }}
/>