Login Key Samples

Code samples in JavaScript, C#, Java, and Python for generating a time-limited Glance Login Key on your server.

Login Key Samples

Visit Glance Login Key Check to view an HTML page with a form to generate and test login keys.

The page may be saved and used locally since the key generation is carried out in the browser-side JavaScript, and the page does not make server requests. To see working code that generates a Login Key, please refer to the JavaScript source.

JavaScript Example

To use this JavaScript function in a browser you must load the crypto-js.js script from the crypto-js package. It may be available on a content delivery network like cdnjs.

JAVASCRIPT
CryptoJS.enc.Base64._map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=';

function GenerateLoginKey(partnerId, partnerUserId, expirationSeconds, apikey) {
    var version = 1;
    var expiration = Math.round(Date.now() * 0.001) + expirationSeconds;
    var keystring = partnerId.toString()
           + partnerUserId.toString()
           + version.toString()
           + expiration.toString();
           
    var hmac = CryptoJS.HmacSHA256(keystring, apikey);
    var hmacb64 = hmac.toString(CryptoJS.enc.Base64);
    
    var loginkey = "$" + version
           + "$" + expiration
           + "$" + hmacb64.substr(0, 43);
           
    console.log(loginkey);
}

GenerateLoginKey(98765, "UserId", 7200, "RedactedApiKey");

To use it in server code on a Node.js server:

  1. Run npm install crypto-js --save in your project.
  2. Put these require() lines before the function:
JAVASCRIPT
var CryptoJS = require("crypto-js");
var HmacSHA256 = require('crypto-js/hmac-sha256');
var Base64 = require('crypto-js/enc-base64');

C# Example

CSHARP
public static string GenerateLoginKey(int partnerId, string partnerUserId, 
                                      int expirationSeconds, string apikey)
{
    const int ver = 1;

    DateTime expires = DateTime.Now.AddSeconds(expirationSeconds);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    int expiration = Convert.ToInt32((expires.ToUniversalTime() - epoch).TotalSeconds);

    string message = partnerId.ToString() + partnerUserId.ToString() + ver.ToString() 
                     + expiration.ToString();
                     
    var encoding = new System.Text.UTF8Encoding();
    var hmac = new System.Security.Cryptography.HMACSHA256(encoding.GetBytes(apikey));

    string hash = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(message)));

    hash = hash.Substring(0, 43).Replace('+', '-').Replace('/', '_');   // base64url no padding

    string loginkey = '$' + ver.ToString() + '$' + expiration.ToString() + '$' + hash;
    return loginkey;
}

Java Example

JAVA
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import javax.crypto.Mac;
import javax.crypto.spec.*;
import java.util.Base64;

public class LoginKey {
    public static void main(String[] args) {
      String key = GenerateLoginKey(1, "bronan", 7200, "RedactedApiKey");
      System.out.println(key);
    }
    
    public static String GenerateLoginKey(int partnerId, String partnerUserId, 
                                          int expirationSeconds, String apikey) {
      int ver = 1;
      int timestamp = Math.toIntExact(Instant.now().getEpochSecond());
      int expiration = timestamp + expirationSeconds;
      String message = String.valueOf(partnerId)
                     + String.valueOf(partnerUserId)
                     + String.valueOf(ver)
                     + String.valueOf(expiration);
      try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(apikey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        
        String hash = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));
        hash = hash.substring(0, 43)
                   .replace('+', '-')
                   .replace('/', '_');
                   
        return '$' + String.valueOf(ver)
             + '$' + String.valueOf(expiration)
             + '$' + hash;
             
      } catch (Exception e) {
          System.out.print(e.getMessage());
          return "Error";
      }
    }
}

Python Example

PYTHON
import time
import hmac
from hashlib import sha256
import base64

def generateLoginKey(partnerId, partnerUserId, expirationSeconds, apikey):
    ver = 1
    timestamp = int(time.time())
    expiration = timestamp + expirationSeconds
    message = str(partnerId) \
            + str(partnerUserId) \
            + str(ver) \
            + str(expiration)
            
    hmac_bytes = hmac.new(bytes(apikey, "utf-8"), 
                          msg=bytes(message, "utf-8"), 
                          digestmod=sha256).digest()
                          
    hash = base64.b64encode(hmac_bytes).decode('ascii')
    hash = hash[:43].replace('+', '-').replace('/', '_')
    
    return '$' + str(ver) \
         + '$' + str(expiration) \
         + '$' + hash

print(generateLoginKey(98765, "UserId", 7200, "RedactedApiKey"))