Nezam.SecureHttpClients
1.0.2
dotnet add package Nezam.SecureHttpClients --version 1.0.2
NuGet\Install-Package Nezam.SecureHttpClients -Version 1.0.2
<PackageReference Include="Nezam.SecureHttpClients" Version="1.0.2" />
<PackageVersion Include="Nezam.SecureHttpClients" Version="1.0.2" />
<PackageReference Include="Nezam.SecureHttpClients" />
paket add Nezam.SecureHttpClients --version 1.0.2
#r "nuget: Nezam.SecureHttpClients, 1.0.2"
#:package Nezam.SecureHttpClients@1.0.2
#addin nuget:?package=Nezam.SecureHttpClients&version=1.0.2
#tool nuget:?package=Nezam.SecureHttpClients&version=1.0.2
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
- 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.
Product | Versions 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. |
-
net8.0
- Microsoft.Extensions.Configuration (>= 8.0.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Logging (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Initial release with secure HTTP client implementation