Generate Signature
Authentication is required for all requests to the Miden API. It ensures that only authorized users or applications can access Miden services and interact with sensitive financial data. The authentication process involves two key components: Token Generation and Request Signature Generation.
Overview
To begin interacting with the Miden API, you must first obtain an access token. This is done by sending a request to the Get Token endpoint with valid credentials. If the request is successful, Miden will return an access token that grants temporary access to protected API endpoints. The access token must be included in the Authorization header of all subsequent API requests.

Usage:
Signature is essential for all API requests and must be included in the header of each request to ensure successful communication with the API. By generating a unique signature for each call, you authenticate your request, verify its integrity, and protect sensitive data from unauthorized access. This practice is crucial for maintaining the security and reliability of your interactions with the API, ensuring that only legitimate requests are processed.
How to generate Your signature:
When you interact with our API, generating a signature is crucial for authentication. This guide will help you understand how to create a signature using code samples in different programming languages.
Step-by-step process:
1
Understand the signature structure:
The signature is generated by combining several components:
a. HTTP Method (GET, POST, etc.)
b. Full URL of the request
c. A unique reference string
d. Your client ID
e. Your client secret
These components are concatenated in a specific order, hashed, and then encoded to produce the final signature.
2
Generate the unique reference:
The reference is a unique string that helps ensure that each request is distinct. This can be generated using a nonce function that produces random strings.
3
Create the base string:
The base string to be signed is constructed using this format:
HTTP_METHOD&ENCODED_URL&REFERENCE&CLIENT_ID&CLIENT_SECRET
4
Hashing and encoding
The base string is hashed using SHA-1, and the resulting hash is then encoded in Base64.
5
Code samples
Here are code snippets in PHP, Go, C#, and JavaScript (Node.js) to help you generate the signature.
//Generate AuthToken
$credentials = $clientId . ':' . $clientSecret;
$authorizationHeader = 'Basic ' . base64_encode($credentials);
$apiResponse = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => $authorizationHeader,
])->asForm()->post($tokenUrl, [
'grant_type' => 'client_credentials',
'scope' => 'CardAPIs',
]);
//Calculate signature
$url = "full url of the request";
$encodeUrl = urlencode($url);
$reference = nonce();
$clientId = "client Id generated during application creation";
$clientSecret = "generated during application creation";
$method = "Http method of the request";
$baseStringToBeSigned = $method . "&" . $encodeUrl . "&" . $reference. "&". $clientId . "&" . $clientSecret;
$signature = Base64Encode(SHA1Here($baseStringToBeSigned));
function nonce()
{
return substr(str_shuffle(MD5(microtime())), 0, 20);
}
function Base64Encode($value): string
{
return base64_encode($value);
}
function Base64Decode($value): bool|string
{
return base64_decode($value);
}
function SHA256($signaturecipher): bool|string
{
return hash("sha256",$signaturecipher);
}
function SHA1Here($signatureCipher): string
{
return sha1($signatureCipher, false);
}
package main
import (
"bytes"
"encoding/base64"
"fmt"
"net/http"
"net/url"
)
func main() {
url := "token_url"
clientID := "your_client_id"
clientSecret := "your_client_secret"
credentials := clientID + ":" + clientSecret
authHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(credentials))
client := &http.Client{}
reqBody := url.Values{
"scope": []string{"CardAPIs"},
"grant_type": []string{"client_credentials"},
}
req, err := http.NewRequest("POST", url, bytes.NewBufferString(reqBody.Encode()))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", authHeader)
response, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer response.Body.Close()
fmt.Println("Response status:", response.Status)
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
fmt.Println("Response body:", buf.String())
}
//Calculate signature
package main
import (
"fmt"
"math/rand"
"time",
"crypto/sha1"
"encoding/hex"
)
func main() {
url := "full url of the request"
encodeUrl := url // Assuming URL encoding is not necessary in Go
reference := nonce()
clientId := "client Id generated during application creation"
clientSecret := "generated during application creation"
method := "Http method of the request"
baseStringToBeSigned := fmt.Sprintf("%s&%s&%s&%s&%s", method, encodeUrl, reference, clientId, clientSecret)
signature := sha1Here(baseStringToBeSigned)
fmt.Println("Signature:", signature)
}
func nonce() string {
rand.Seed(time.Now().UnixNano())
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, 20)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func sha1Here(data string) string {
hasher := sha1.New()
hasher.Write([]byte(text))
bytes := hasher.Sum(nil)
return hex.EncodeToString(bytes)
}
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
var client = new HttpClient();
var credentials = clientId + ":" + clientSecret;
client.DefaultRequestHeaders.Add("Authorization", $"Basic {Base64Encode(credentials)}");
var data = new[]
{
new KeyValuePair<string, string>("scope", "CardAPIs"),
new KeyValuePair<string, string>("grant_type", "client_credentials"),
};
var apiResponse = await client.PostAsync(url, new FormUrlEncodedContent(data));
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
//Calculate Signature
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string url = "full url of the request";
string encodeUrl = WebUtility.UrlEncode(url);
string reference = Nonce();
string clientId = "client Id generated during application creation";
string clientSecret = "generated during application creation";
string method = "Http method of the request";
string baseStringToBeSigned = $"{method}&{encodeUrl}&{reference}&{clientId}&{clientSecret}";
string signature = Base64Encode(SHA1Here(baseStringToBeSigned));
Console.WriteLine($"Signature: {signature}");
}
static string Nonce()
{
return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 20);
}
static string SHA1Here(string data)
{
var sh = SHA1.Create();
var hash = new StringBuilder();
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] b = sh.ComputeHash(bytes);
foreach (byte a in b)
{
var h = a.ToString("x2");
hash.Append(h);
}
return hash.ToString();
}
}
//Signature Calculation
exports.generateSignature = async (url, method) => {
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const encodeUrl = encodeURIComponent(url);
const reference = nonce();
const clientId = `${process.env.MIDEN_CLIENT_ID}`
const clientSecret = `${process.env.MIDEN_SECRET_KEY_TEST}`
const baseStringToBeSigned = `${method}&${encodeUrl}&${reference}&${clientId}&${clientSecret}`;
const hashValue = textToHash(baseStringToBeSigned);
const signature = toBase64(hashValue);
function nonce() {
return uuidv4().replace(/-/g, '').substring(0, 20);
}
function sha1(data) {
return crypto.createHash('sha1').update(data).digest('base64');
}
function textToHash(text) {
const hash = crypto.createHash('sha1'); // Create SHA-1 hash object
hash.update(text, 'utf8'); // Update the hash with the text encoded in UTF-8
const hashHex = hash.digest('hex'); // Get the resulting hash as a hexadecimal string
return hashHex;
}
function toBase64(input) {
return Buffer.from(input).toString('base64');
}
return signature
}
import base64
import hashlib
import requests
import urllib.parse
import uuid
# ========== CONFIGURATION ==========
client_id = "your_client_id"
client_secret = "your_client_secret"
token_url = "https://your-auth-url.com/token"
scope = "CardAPIs"
request_method = "POST"
target_url = "https://your-api-url.com/endpoint" # Full URL of the actual API request
# ========== GET AUTH TOKEN ==========
def get_access_token():
credentials = f"{client_id}:{client_secret}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
headers = {
"Authorization": f"Basic {encoded_credentials}",
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
"scope": scope
}
response = requests.post(token_url, headers=headers, data=data)
response.raise_for_status()
return response.json()["access_token"]
# ========== GENERATE NONCE ==========
def generate_nonce():
return uuid.uuid4().hex[:20]
# ========== SIGNATURE UTILITIES ==========
def sha1_hash(text: str) -> str:
return hashlib.sha1(text.encode('utf-8')).hexdigest()
def base64_encode(text: str) -> str:
return base64.b64encode(text.encode('utf-8')).decode()
# ========== GENERATE SIGNATURE ==========
def generate_signature(method: str, url: str, ref: str, client_id: str, client_secret: str) -> str:
encoded_url = urllib.parse.quote(url, safe='') # equivalent of WebUtility.UrlEncode or urlencode
base_string = f"{method}&{encoded_url}&{ref}&{client_id}&{client_secret}"
sha1_result = sha1_hash(base_string)
return base64_encode(sha1_result)
# ========== MAIN ==========
if __name__ == "__main__":
# Get Access Token
token = get_access_token()
print("Access Token:", token)
# Generate Signature
reference = generate_nonce()
signature = generate_signature(request_method, target_url, reference, client_id, client_secret)
print("Reference:", reference)
print("Signature:", signature)
Signature Calculation:
//Signature Calculation
exports.generateSignature = async (url, method) => {
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const encodeUrl = encodeURIComponent(url);
const reference = nonce();
const clientId = ${process.env.MIDEN_CLIENT_ID}
const clientSecret = ${process.env.MIDEN_SECRET_KEY_TEST}
const baseStringToBeSigned = ${method}&${encodeUrl}&${reference}&${clientId}&${clientSecret};
const hashValue = textToHash(baseStringToBeSigned);
const signature = toBase64(hashValue);
function nonce() {
return uuidv4().replace(/-/g, '').substring(0, 20);
}
function textToHash(text) {
const hash = crypto.createHash('sha1'); // Create SHA-1 hash object
hash.update(text, 'utf8'); // Update the hash with the text encoded in UTF-8
const hashHex = hash.digest('hex'); // Get the resulting hash as a hexadecimal string
return hashHex;
}
function toBase64(input) {
return Buffer.from(input).toString('base64');
}
return signature
}
- 'ref' is the reference passed in the header as part of the request. Hence:
- url encode the full url
- proceed to concatenate the verb, url, reference, clientId and secret.
- Finally, get a SHA1 of the concatenated string and then encode it as base64 string.
- Ensure that full values are being passed in the URL.
- Some code snippets might contain placeholder values for sensitive information like API keys. Remember to replace these placeholders with your actual credentials before using the code.
- All Request Methods passed must be in Uppercase.
On this page
- Generate Signature