Nezam.SecureHttpClients 1.0.2

dotnet add package Nezam.SecureHttpClients --version 1.0.2
                    
NuGet\Install-Package Nezam.SecureHttpClients -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Nezam.SecureHttpClients" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nezam.SecureHttpClients" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Nezam.SecureHttpClients" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Nezam.SecureHttpClients --version 1.0.2
                    
#r "nuget: Nezam.SecureHttpClients, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Nezam.SecureHttpClients@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Nezam.SecureHttpClients&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Nezam.SecureHttpClients&version=1.0.2
                    
Install as a Cake Tool

Nezam Secure HTTP Clients

A highly customizable and configurable HTTP client library for secure communication with Nezam web services. This library provides automatic signature generation, retry logic, custom JSON serialization, and extensive request customization capabilities.

Features

  • 🔐 Automatic Signature Generation - Secure API communication with HMAC signatures
  • ⚙️ Fully Configurable - Custom JSON serialization, headers, timeouts, and more
  • 🔄 Retry Logic - Configurable retry policies with exponential backoff
  • 🎯 Request Context - Per-request customization with headers, timeouts, and interceptors
  • 🚀 High Performance - Optimized HTTP client with connection pooling
  • 📝 Comprehensive Logging - Detailed request/response logging
  • 🛡️ Error Handling - Custom error handlers and response interceptors
  • 🔧 Extensible - Custom HTTP message handlers and interceptors

Installation

Add the package to your project:

dotnet add package Nezam.SecureHttpClients

Quick Start

1. Register Services

In your Program.cs or Startup.cs:

using Nezam.SecureHttpClients.Extensions;

// Register with configuration
builder.Services.AddNezamApiClient(builder.Configuration);

// Or register with custom configuration
builder.Services.AddNezamApiClient(options =>
{
    options.BaseUrl = "https://api.nezam.com";
    options.TenantCode = "AHMADI";
    options.ApiKey = "your-api-key";
    options.SecretKey = "your-secret-key";
    options.TimeoutSeconds = 30;
    options.EnableDetailedLogging = true;
});

2. Configuration

In appsettings.json:

{
  "NezamApi": {
    "BaseUrl": "https://api.nezam.com",
    "TenantCode": "AHMADI",
    "ApiKey": "your-api-key",
    "SecretKey": "your-secret-key",
    "PublicKey": "your-public-key",
    "TimeoutSeconds": 30,
    "MaxTimestampDifferenceMinutes": 5,
    "EnableRetry": true,
    "MaxRetryAttempts": 3,
    "RetryDelayMs": 1000,
    "EnableDetailedLogging": true
  }
}

3. Use the Client

public class UserService
{
    private readonly INezamApiClient _apiClient;

    public UserService(INezamApiClient apiClient)
    {
        _apiClient = apiClient;
    }

    public async Task<UserResponse?> GetUserAsync(int id)
    {
        return await _apiClient.GetAsync<UserResponse>($"/api/users/{id}");
    }

    public async Task<UserResponse?> CreateUserAsync(CreateUserRequest request)
    {
        return await _apiClient.PostAsync<CreateUserRequest, UserResponse>("/api/users", request);
    }

    public async Task UpdateUserAsync(int id, UpdateUserRequest request)
    {
        await _apiClient.PutAsync($"/api/users/{id}", request);
    }

    public async Task DeleteUserAsync(int id)
    {
        await _apiClient.DeleteAsync($"/api/users/{id}");
    }
}

Advanced Usage

Multiple Clients

Register multiple clients with different configurations:

builder.Services.AddNezamApiClients(builder.Configuration, "Production", "Staging");

Configuration:

{
  "NezamApi": {
    "Production": {
      "BaseUrl": "https://api.nezam.com",
      "TenantCode": "AHMADI",
      "ApiKey": "prod-api-key",
      "SecretKey": "prod-secret-key"
    },
    "Staging": {
      "BaseUrl": "https://staging-api.nezam.com",
      "TenantCode": "AHMADI",
      "ApiKey": "staging-api-key",
      "SecretKey": "staging-secret-key"
    }
  }
}

Direct Signature Management

Use the signature manager directly for custom scenarios:

public class CustomSignatureService
{
    private readonly ISignatureManager _signatureManager;

    public CustomSignatureService(ISignatureManager signatureManager)
    {
        _signatureManager = signatureManager;
    }

    public async Task<string> CreateCustomSignatureAsync(string method, string path, string body)
    {
        var signatureInfo = _signatureManager.CreateSecureSignature(
            method, 
            path, 
            body: body, 
            tenantCode: "AHMADI", 
            secretKey: "your-secret-key",
            includeNonce: true
        );

        return signatureInfo.Signature;
    }

    public bool ValidateCustomSignature(string method, string path, string body, string signature, string timestamp)
    {
        return _signatureManager.ValidateCompleteSignature(
            method, 
            path, 
            body: body, 
            signature: signature, 
            timestamp: timestamp, 
            secretKey: "your-secret-key"
        );
    }
}

Signature Types

HMAC-SHA256 (Default)

Uses a shared secret key for signing and validation:

// Generate signature
var signature = _signatureManager.GenerateSignature(payload, secretKey);

// Validate signature
var isValid = _signatureManager.ValidateSignature(payload, signature, secretKey);

RSA-SHA256

Uses private/public key pairs for asymmetric signing:

// Generate signature with private key
var signature = _signatureManager.GenerateRsaSignature(payload, privateKey);

// Validate signature with public key
var isValid = _signatureManager.ValidateRsaSignature(payload, signature, publicKey);

Security Features

Timestamp Validation

Prevents replay attacks by validating request timestamps:

var timestamp = _signatureManager.GenerateTimestamp();
var isValid = _signatureManager.ValidateTimestamp(timestamp, maxMinutesDifference: 5);

Nonce Generation

Adds uniqueness to requests to prevent replay attacks:

var nonce = _signatureManager.GenerateNonce();
var isValid = _signatureManager.ValidateNonce(nonce);

Complete Signature Validation

Validates all components of a request signature:

var isValid = _signatureManager.ValidateCompleteSignature(
    method: "POST",
    path: "/api/users",
    body: "{\"name\":\"John\"}",
    signature: "abc123...",
    timestamp: "1704067200",
    secretKey: "your-secret-key"
);

Configuration Options

Option Type Default Description
BaseUrl string - Base URL of the API
TenantCode string - Tenant code for requests
ApiKey string - API key for authentication
SecretKey string - Secret key for HMAC signatures
PublicKey string - Public key for RSA validation
TimeoutSeconds int 30 HTTP request timeout
MaxTimestampDifferenceMinutes int 5 Maximum allowed timestamp difference
EnableRetry bool true Enable automatic retry
MaxRetryAttempts int 3 Maximum retry attempts
RetryDelayMs int 1000 Delay between retries
EnableDetailedLogging bool false Enable detailed logging

Error Handling

The client automatically handles common errors and provides detailed logging:

try
{
    var response = await _apiClient.PostAsync<LoginRequest, LoginResponse>("/api/auth/login", request);
    if (response != null)
    {
        // Success
    }
}
catch (HttpRequestException ex)
{
    // Handle HTTP errors
    _logger.LogError(ex, "HTTP request failed");
}

Logging

Enable detailed logging to debug signature generation and validation:

{
  "Logging": {
    "LogLevel": {
      "Nezam.SecureHttpClients": "Debug"
    }
  }
}

Best Practices

  1. Secure Key Storage: Store API keys and secrets in secure configuration providers (Azure Key Vault, AWS Secrets Manager, etc.)
  2. Key Rotation: Regularly rotate API keys and secrets
  3. Timestamp Validation: Always validate timestamps to prevent replay attacks
  4. Nonce Usage: Use nonces for high-security scenarios
  5. Error Handling: Implement proper error handling for failed requests
  6. Logging: Use structured logging for better monitoring
  7. Retry Policies: Configure appropriate retry policies for your use case

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 186 7/20/2025
1.0.1 183 7/20/2025
1.0.0 181 7/20/2025

Initial release with secure HTTP client implementation