Implementing Akamai EdgeGrid Authentication for Secure REST API Access

Understanding Akamai EdgeGrid Authentication

EdgeGrid Auth is a custom authentication protocol designed to secure API requests sent too Akamai endpoints. Unlike standard Bearer tokens, it employs a cryptographic signing process to verify the integrity and authenticity of every request.

Core Components

  • Signing Key and HMAC-SHA256: The security relies on a shared secret (Client Secret) known only to the client and Akamai. An HMAC-SHA256 signature is generated using this secret, combined with specific request data. This ensures that the request cannot be tampered with during transit.
  • Timestamp and Nonce: To prevent replay attacks, every request includes a timestamp (indicating when the request was made) and a nonce (a unique cryptographic token). Even if an attacker intercepts a request, they cannot reuse it because the server will reject duplicates or expired timestamps.
  • Client Token and Access Token: These identifiers are passed in the header to tell Akamai which client is making the request and which level of access they possess.

Implementation Strategies

Implementing EdgeGrid requires constructing a specific Authorization header. The format typically follows:

EG1-HMAC-SHA256 clientToken={client_token};accessToken={access_token};timestamp={timestamp};nonce={nonce};signature={signature}

Below are implemantation examples in Python, Java, and Go. Note that these examples replace the generic JWT approach with the correct EdgeGrid signing algorithm using standard cryptographic libraries.

Python Implementation

For Python, we use the hmac and hashlib modules to generate the signature.

import hmac
import hashlib
import base64
import time
import uuid
import requests

def generate_edgegrid_header(host, path, method, client_token, access_token, client_secret, request_body=""):
    # 1. Create Timestamp and Nonce
    timestamp = int(time.time())
    nonce = str(uuid.uuid4())

    # 2. Construct the data to sign (simplified)
    # In a real scenario, headers must be sorted and joined with newlines
    data_to_sign = f"{method} {path}\nhost: {host}\n\n{request_body}"

    # 3. Generate the Signature
    decoded_secret = base64.b64decode(client_secret)
    digest = hmac.new(decoded_secret, data_to_sign.encode('utf-8'), hashlib.sha256).digest()
    signature = base64.b64encode(digest).decode('utf-8')

    # 4. Construct the Authorization Header value
    auth_header = (
        f"EG1-HMAC-SHA256 clientToken={client_token};"
        f"accessToken={access_token};"
        f"timestamp={timestamp};"
        f"nonce={nonce};"
        f"signature={signature}"
    )
    return auth_header

# Usage
host = "your-api-host"
endpoint = "/your-api-path"
secret = "your_base64_encoded_secret"
token = generate_edgegrid_header(host, endpoint, "GET", "client_token", "access_token", secret)

headers = {'Authorization': token}
response = requests.get(f"https://{host}{endpoint}", headers=headers)
print(response.status_code)

Java Implementation

Java provides robust cryptography support through javax.crypto. Here is how to construct the header.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

public class AkamaiAuth {

    public static String createAuthHeader(String host, String path, String method, 
                                          String clientToken, String accessToken, String secret) throws Exception {
        // 1. Timestamp and Nonce
        long timestamp = System.currentTimeMillis() / 1000;
        String nonce = UUID.randomUUID().toString();

        // 2. Data to sign
        String dataToSign = method + " " + path + "\nhost: " + host + "\n\n";

        // 3. Calculate Signature
        byte[] decodedSecret = Base64.getDecoder().decode(secret);
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(decodedSecret, "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] signatureBytes = Base64.getEncoder().encode(sha256_HMAC.doFinal(dataToSign.getBytes(StandardCharsets.UTF_8)));
        String signature = new String(signatureBytes);

        // 4. Build Header
        return String.format("EG1-HMAC-SHA256 clientToken=%s;accessToken=%s;timestamp=%d;nonce=%s;signature=%s",
                clientToken, accessToken, timestamp, nonce, signature);
    }
}

Go Implementation

Go's standard library offers excellent support for HMAC and SHA256 operations required for EdgeGrid.

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"time"
	"github.com/google/uuid"
)

func GetAuthHeader(host, path, method, clientToken, accessToken, secret string) (string, error) {
	// 1. Timestamp and Nonce
	ts := time.Now().Unix()
	nc := uuid.New().String()

	// 2. Construct Signing Data
	dataToSign := fmt.Sprintf("%s %s\nhost: %s\n\n", method, path, host)

	// 3. Compute HMAC-SHA256 Signature
	decodedSecret, _ := base64.StdEncoding.DecodeString(secret)
	h := hmac.New(sha256.New, decodedSecret)
	h.Write([]byte(dataToSign))
	signature := base64.StdEncoding.EncodeToString(h.Sum(nil))

	// 4. Format Header
	return fmt.Sprintf("EG1-HMAC-SHA256 clientToken=%s;accessToken=%s;timestamp=%d;nonce=%s;signature=%s",
		clientToken, accessToken, ts, nc, signature), nil
}

Testing Your Implementation

After implementing the signing logic, validating it against the actual Akamai APIs is crucial. The following tools can assist in this process.

Testing with Apipost

Apipost offers built-in support for EdgeGrid, simplifying the testing process without writing custom scripts.

  1. Configuration: Create a new request and navigate to the "Auth" tab.
  2. Select Type: Choose Akamai EdgeGrid from the authentication dropdown.
  3. Enter Credentials:
    • Acces Token: Your Akamai Access Token.
    • Client Token: Your Akamai Client Token.
    • Client Secret: The Base64 encoded secret key.
  4. Advanced Settings: You can manually specify the Nonce, Timestamp, and Headers to Sign if the default auto-generation does not fit your specific scenario.
  5. Execution: Send the request. Apipost handles the signing automatically. A 200 OK response indicates your credentials and the endpoint configuration are correct.

Testing with Postman

While Postman does not have a native "Akamai EdgeGrid" button, you can test it effectively by using the code generated above.

  1. Generate Header: Use your implementation script (Python/Java/Go) to generate the Authorization string for your current timestamp.
  2. Setup Request: In Postman, set the HTTP method and URL.
  3. Headers: Add a header key Authorization and paste the generated string as the value.
  4. Send: Execute the request. If the signature calculation in your code matches the server's expectation, the request will succeed.

Testing with cURL

For command-line testing, cURL is the most direct tool.

curl -X GET "https://your-api-host/your-path" \
-H "Authorization: EG1-HMAC-SHA256 clientToken=xxx;accessToken=yyy;timestamp=zzz;nonce=aaa;signature=bbb"

Ensure the Authorization header value is freshly generated before running the command, otherwise, the timestamp validation will fail.

Tags: Akamai EdgeGrid REST API API Security HMAC-SHA256

Posted on Mon, 27 Jul 2026 16:44:29 +0000 by zmola