Big News: Socket Selected for OpenAI's Cybersecurity Grant Program.Details
Socket
Book a DemoSign in
Socket

Nezam.SecureHttpClients

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

Nezam.SecureHttpClients

Secure HTTP client library for Nezam applications with authentication, retry policies, and circuit breaker patterns.

Source
nugetNuGet
Version
1.0.2
Version published
Maintainers
1
Created
Source

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

OptionTypeDefaultDescription
BaseUrlstring-Base URL of the API
TenantCodestring-Tenant code for requests
ApiKeystring-API key for authentication
SecretKeystring-Secret key for HMAC signatures
PublicKeystring-Public key for RSA validation
TimeoutSecondsint30HTTP request timeout
MaxTimestampDifferenceMinutesint5Maximum allowed timestamp difference
EnableRetrybooltrueEnable automatic retry
MaxRetryAttemptsint3Maximum retry attempts
RetryDelayMsint1000Delay between retries
EnableDetailedLoggingboolfalseEnable 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

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

Contributing

  • Fork the repository
  • Create a feature branch
  • Make your changes
  • Add tests
  • Submit a pull request

License

This project is licensed under the MIT License.

Keywords

http-client

FAQs

Package last updated on 20 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts