Introduction
Applications built with .NET often communicate with AWS services through the AWS SDK for .NET. The SDK provides service-specific clients that handle authentication, request serialization, retries, and response processing. However, there are situations where an application needs to call an AWS endpoint directly using HttpClient.
For example, an application might need to call an IAM-protected API Gateway endpoint, invoke a Lambda function URL, or communicate with Amazon OpenSearch Service through a custom HTTP integration. In these situations, the application still needs to authenticate the request using AWS Signature Version 4, commonly known as SigV4.
Implementing SigV4 manually is not a simple task. It involves creating a canonical request, calculating SHA-256 hashes, deriving a signing key, and generating an HMAC signature. Small differences in the URL, headers, payload, or timestamp can cause AWS to reject the request.
The AWS SDK for .NET provides a standalone SigV4 signer that makes this process easier. It allows developers to sign HTTP requests without creating a service-specific SDK client.
In this article, we will explore how SigV4 works, how to use the standalone signer with HttpClient, and how to configure automatic request signing through a DelegatingHandler.
What Is AWS Signature Version 4?
AWS Signature Version 4 is an authentication mechanism used by AWS services to verify that an HTTP request comes from an authorized identity.
When an application sends a request to an AWS service, it must provide authentication information. SigV4 creates a cryptographic signature using the request details and AWS credentials.
The signature helps AWS verify that:
- The request was signed using valid credentials.
- The request has not been modified after signing.
- The request targets the intended AWS service and Region.
- The request was created within an acceptable time window.
The signing process uses the HTTP method, request path, query parameters, selected headers, and payload hash.
For example, a request to an IAM-protected API Gateway endpoint might contain an Authorization header with the generated signature, along with additional headers such as X-Amz-Date.
For temporary credentials, the request also needs the X-Amz-Security-Token header.
Understanding the SigV4 Signing Process
Before using the .NET signer, it helps to understand what happens internally.
The standard SigV4 process consists of several steps.
Create a canonical request
AWS first converts the HTTP request into a standardized representation called a canonical request.
It includes:
- HTTP method, such as GET or POST.
- Canonical URI.
- Canonical query string.
- Canonical headers.
- Signed header names.
- SHA-256 hash of the request payload.
This ensures that the application and AWS service calculate the signature using the same request information.
Create a string to sign
The signer creates a string containing the signing algorithm, request timestamp, credential scope, and hash of the canonical request.
The credential scope includes the request date, AWS Region, service name, and the aws4_request identifier.
Derive the signing key
The signing key is derived from the AWS secret access key using a sequence of HMAC-SHA256 operations.
The process incorporates the request date, Region, and service name.
Generate the signature
The signer uses the derived key to calculate the final signature.
The signature is then included in the Authorization header or, when using presigned requests, in the query string.
The AWS SDK handles these operations automatically through its public signing APIs.
Installing the AWS SDK Signing Package
The standalone SigV4 signer is included in the AWS SDK for .NET Core package.
It was introduced in AWSSDK.Core version 4.0.101.0. Therefore, use that version or a later compatible release.
Install the package using the .NET CLI:
dotnet add package AWSSDK.Core --version 4.0.101.0If your application already uses another AWS service package, AWSSDK.Core is normally included as a dependency. In that case, update the existing dependency to a version that provides the standalone signer.
The signing APIs are available in the following namespaces:
using Amazon;
using Amazon.Runtime.Credentials;
using Amazon.Runtime.Signing;The main types used in this article are:
| Type | Purpose |
|---|---|
| AWSSigningRequest | Describes the HTTP request to sign |
| AWSSigV4Parameters | Contains credentials, Region, and service information |
| AWSSigV4Signer | Generates the SigV4 signature |
| AWSSigningResult | Contains the generated request headers |
| SigV4SigningHandler | Automatically signs outgoing HttpClient requests |
Signing an HTTP Request Manually
Let's start with a practical example.
Suppose an application needs to call the AWS Security Token Service GetCallerIdentity operation using HttpClient instead of an STS service client.
The request uses the AWS Query API endpoint and requires SigV4 authentication.
The following example creates the signing request:
using Amazon;
using Amazon.Runtime.Credentials;
using Amazon.Runtime.Signing;
var signingRequest = new AWSSigningRequest
{
HttpMethod = HttpMethod.Get,
RequestUri = new Uri(
"https://sts.us-east-1.amazonaws.com/" +
"?Action=GetCallerIdentity" +
"&Version=2011-06-15")
};
var parameters = new AWSSigV4Parameters
{
Credentials =
DefaultAWSCredentialsIdentityResolver.GetCredentials(),
Region = RegionEndpoint.USEast1,
Service = "sts"
};
AWSSigningResult signingResult =
await AWSSigV4Signer.SignAsync(
signingRequest,
parameters);The AWSSigningRequest describes the HTTP method and complete request URI.
AWSSigV4Parameters provides the information required to generate the signature.
The example uses DefaultAWSCredentialsIdentityResolver to obtain credentials from the standard AWS credential resolution chain. Depending on the environment, credentials may come from environment variables, shared AWS configuration, an IAM role, or another supported provider.
The Region is set to US East (N. Virginia), and the service name is sts.
The SignAsync method generates the signature and returns the headers that must be included in the outgoing request.
Sending the Signed Request Using HttpClient
Generating the signature does not send the HTTP request. The application must apply the returned headers and then use HttpClient to communicate with AWS.
Continue with the following code:
using System.Net.Http;
var message = new HttpRequestMessage(
HttpMethod.Get,
signingRequest.RequestUri);
foreach (var header in signingResult.Headers)
{
message.Headers.TryAddWithoutValidation(
header.Key,
header.Value);
}
using var httpClient = new HttpClient();
using var response = await httpClient.SendAsync(message);
string responseBody =
await response.Content.ReadAsStringAsync();
Console.WriteLine(
$"Status: {response.StatusCode}");
Console.WriteLine(responseBody);
response.EnsureSuccessStatusCode();The application creates an HttpRequestMessage using the same HTTP method and URI that were used during signing.
It then adds every header returned by the signer.
This is important because the signing result can contain more than the Authorization header. It may also include X-Amz-Date and X-Amz-Security-Token when temporary credentials are used.
Adding only the Authorization header can cause AWS to reject the request because other required signed headers are missing.
After applying the headers, HttpClient sends the request and reads the response.
This approach is useful when an application needs complete control over how individual HTTP requests are created and sent.
Automatically Signing Requests With SigV4SigningHandler
Manually signing every request can become repetitive when an application communicates with an AWS endpoint frequently.
For example, an ASP.NET Core application may send dozens of requests to an IAM-protected API Gateway endpoint. Adding signing logic before every HttpClient.SendAsync call makes the code harder to maintain.
The AWS SDK provides SigV4SigningHandler, which is a DelegatingHandler that signs outgoing requests automatically.
You can configure the handler once and continue using normal HttpClient methods.
using Amazon;
using Amazon.Runtime.Credentials;
using Amazon.Runtime.Signing;
using System.Text;
var credentials =
DefaultAWSCredentialsIdentityResolver.GetCredentials();
var signingHandler = new SigV4SigningHandler(
credentials,
RegionEndpoint.USEast1,
service: "execute-api");
using var httpClient = new HttpClient(signingHandler);
var requestBody = new
{
Name = "Sample Product",
Price = 1200
};
string json = System.Text.Json.JsonSerializer.Serialize(
requestBody);
using var content = new StringContent(
json,
Encoding.UTF8,
"application/json");
using var response = await httpClient.PostAsync(
"https://abc123.execute-api.us-east-1.amazonaws.com/prod/items",
content);
response.EnsureSuccessStatusCode();
Console.WriteLine("Request completed successfully.");The handler is configured with AWS credentials, Region, and service name.
The service name for API Gateway is execute-api.
When PostAsync is called, the handler signs the request before sending it. The request body is also included in the signing process by default.
This keeps authentication logic outside the business code and makes the HttpClient implementation easier to read.
The same approach can be used with other AWS endpoints that support SigV4 over HTTP, provided the correct service name and Region are configured.
Using SigV4SigningHandler With IHttpClientFactory
In ASP.NET Core applications, IHttpClientFactory is generally a better choice than creating new HttpClient instances throughout the application.
It provides centralized client configuration, dependency injection support, and handler management.
The signing handler can be registered through the service container.
using Amazon;
using Amazon.Runtime.Credentials;
using Amazon.Runtime.Signing;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient(_ =>
new SigV4SigningHandler(
DefaultAWSCredentialsIdentityResolver.GetCredentials(),
RegionEndpoint.USEast1,
service: "execute-api"));
builder.Services.AddHttpClient("SignedAwsClient")
.AddHttpMessageHandler<SigV4SigningHandler>()
.ConfigurePrimaryHttpMessageHandler(() =>
new SocketsHttpHandler
{
AllowAutoRedirect = false
});
var app = builder.Build();
app.MapGet("/", () => "AWS signed HTTP client is configured.");
app.Run();The signing handler is registered as a transient service and attached to the named HttpClient.
One important detail is automatic redirect handling. When using SigV4SigningHandler directly with HttpClient, its default transport disables automatic redirects. When registering it through IHttpClientFactory, configure the primary SocketsHttpHandler explicitly to disable automatic redirects.
Otherwise, a redirected request could be sent to a different URL without passing through the signing handler again.
For an actual application, place the registration in the service configuration and inject IHttpClientFactory into the service that needs to communicate with AWS.
Using Different AWS Services and Regions
An application may need to communicate with more than one AWS service.
For example, it might call API Gateway in one Region and Amazon S3 in another Region.
Instead of creating a separate handler for every combination, SigV4SigningHandler supports per-request service and Region overrides.
using Amazon.Runtime.Signing;
var request = new HttpRequestMessage(
HttpMethod.Get,
"https://my-bucket.s3.us-west-2.amazonaws.com/sample.txt");
request.Options.Set(
new HttpRequestOptionsKey<string>(
SigV4SigningHandler.ServiceOptionKey),
"s3");
request.Options.Set(
new HttpRequestOptionsKey<string>(
SigV4SigningHandler.RegionOptionKey),
"us-west-2");
using var response = await httpClient.SendAsync(request);The handler uses the service and Region values supplied through the request options instead of its default values.
This is useful when a shared HTTP client needs to communicate with multiple AWS endpoints.
However, the configured credentials must still have permission to access the requested resource.
Handling Large Request Payloads
By default, the standalone signer calculates a hash of the request body and includes it in the signature.
This provides integrity protection because changes to the payload affect the calculated signature.
However, hashing a large request body can require reading the complete content before the request is sent.
For applications that upload large files or use streaming request bodies, this can increase memory usage and delay transmission.
The standalone signer provides a SignPayload option.
var parameters = new AWSSigV4Parameters
{
Credentials =
DefaultAWSCredentialsIdentityResolver.GetCredentials(),
Region = RegionEndpoint.USWest2,
Service = "s3",
SignPayload = false
};When SignPayload is false, the signer uses the UNSIGNED-PAYLOAD value instead of calculating a body hash.
This avoids reading the complete body for hashing, but it also means that the payload itself is not protected by the SigV4 payload hash. HTTPS is required for this mode.
Use this option only when the target AWS service supports the unsigned-payload approach and the application's security requirements allow it.
Another option is to calculate the payload hash in advance and provide it through the appropriate x-amz-content-sha256 header.
Best Practices for Production Applications
Use the correct service name
Every AWS service has an authentication service name. Do not assume that the service name is always the same as its product name.
When an AWS service configuration class is available, its AuthenticationServiceName property can help identify the correct value.
Keep credentials outside source code
Avoid hardcoding AWS access keys and secret keys. Use IAM roles, environment-based credentials, or another supported AWS credential provider.
Sign the final request
The URL, HTTP method, query string, headers, and payload must match the information used during signing.
Do not modify the request after generating the signature.
Apply all signing headers
Always copy every header returned by AWSSigV4Signer. Do not assume that the Authorization header is sufficient.
Handle retries carefully
A SigV4 signature includes a timestamp. If a request must be retried, sign the new attempt again rather than blindly replaying an old signed request.
Be careful with redirects
A redirected request may have a different URL and therefore requires a new signature. Disable automatic redirects or ensure that every redirected request passes through the signing handler.
Use HTTPS
AWS requests should use HTTPS to protect credentials and request data during transmission.
Common Mistakes to Avoid
One common mistake is using the wrong service name or Region. Even when credentials are valid, AWS can reject the request if the signature was generated for a different service or Region.
Another mistake is signing one URI and sending a slightly different URI. Changes to query parameters, request paths, or headers can invalidate the signature.
Developers sometimes copy only the Authorization header and forget the timestamp or temporary security token. Always apply the complete signing result.
A further mistake is manually retrying a request with the same signature. Since the timestamp is part of the signing process, create a fresh signature for each attempt.
Finally, avoid implementing the complete SigV4 algorithm yourself when the public AWS SDK signer is available. Manual implementations introduce unnecessary cryptographic and compatibility risks.
Advantages and Disadvantages
Advantages
- Signs arbitrary HTTP requests without requiring a service-specific AWS SDK client.
- Uses the AWS SDK credential resolution chain.
- Supports both direct request signing and automatic signing through HttpClient.
- Reduces repeated authentication code.
- Supports presigned URLs through the standalone signer.
- Provides payload-signing options for large requests.
Disadvantages
- Developers must provide the correct AWS service name and Region.
- Requests must remain unchanged after signing.
- Redirects and retries require additional care.
- Large payload hashing can increase processing and memory requirements.
- The standalone signer does not replace service-specific SDK functionality such as response models, serialization, and service-specific retry behavior.
Summary
AWS Signature Version 4 is required for many authenticated requests to AWS services. When an application uses a service-specific AWS SDK client, the SDK normally handles signing automatically. However, custom HTTP integrations sometimes require direct access to the signing process.
The standalone SigV4 signer in the AWS SDK for .NET makes this easier through AWSSigV4Signer and SigV4SigningHandler.
Developers can use AWSSigV4Signer to sign individual requests or configure SigV4SigningHandler to sign every outgoing request made through HttpClient.
For ASP.NET Core applications, combining the signing handler with IHttpClientFactory provides a clean way to centralize AWS authentication.
The most important considerations are selecting the correct service and Region, using secure credentials, applying every generated signing header, and ensuring that the request is not modified after signing.

Join the conversation! Your thoughts help the community grow.