Article · 2022-01-05

Third-party API Authentication Using Digest Credentials

The credential field shown in the request contains the digest credential, using the format key:<hash>=version:v1, where the hash is the hexadecimal SHA-256 digest of the client_id. The version component indicates the authentication scheme version, allowing the server to select the appropriate verification algorithm.

Workflow overview:

This design is lightweight: confirming identity requires a single hash computation and comparison. The platform can add new third parties and modify their permissions directly in the database without deploying new code.

{
    "credential": "key:46d47e6c6d8e0c826e214447f80627b6e527c0bfa52323332adb6479c639b5ee=version:v1",
    "page_size": 10,
    "page": 1
}

Credential Generation

import hashlib

client_id = "alpha_secret"  # 示例客户端密钥
digest = hashlib.sha256(client_id.encode('utf-8')).hexdigest()
credential = f"key:{digest}=version:v1"

print(credential)

Server-side Authentication and Authorization

import hashlib

clients_db = {
    "alpha_system": {
        "secret": "alpha_secret",
        "permissions": ["service:getUserContact", "data:listRecords"]
    }
}

def check_credential(credential_str, required_permission):
    try:
        hash_part, version_part = credential_str.split('=', 1)
        version = version_part.split(':', 1)[1]
        provided_hash = hash_part.split(':', 1)[1]
    except Exception:
        return False, "格式错误"

    if version != "v1":
        return False, "版本不支持"

    for name, info in clients_db.items():
        expected_hash = hashlib.sha256(info["secret"].encode()).hexdigest()
        if expected_hash == provided_hash:
            if required_permission in info["permissions"]:
                return True, f"授权成功:{name}"
            return False, "无权限"
    return False, "身份无效"

Security Analysis

Strengths:

Risks:

Future Improvements

Summary

This digest credential scheme satisfies basic authentication and authorization with minimal overhead, suitable for scenarios where performance matters, integration costs are constrained, and the threat environment is relatively controlled. When higher security is required, introduce timestamps, HMAC, signatures, or fine-grained permission models as needed.

© 2026 Yuxu Ge ·