In today’s digital ecosystem, securing credentials is one of the most critical aspects of API development. Weak credential management can lead to data breaches, unauthorized access, and compliance violations. ASP.NET Core provides a robust security framework to help developers safeguard authentication details, API keys, and sensitive configuration settings.
This article explores credential security in ASP.NET Core Web API, covering best practices, real-world implementation, and integration with modern tools like Azure Key Vault.
Why Credential Security Matters
Attack Surface: APIs are often internet-facing, making them prime targets for attackers.
Secrets Leakage: Hardcoding credentials in code or storing them in plain text can expose them via source control (GitHub leaks are typical).
Compliance Risks: Regulations such as GDPR, HIPAA, and PCI DSS mandate secure credential storage.
Goal: Protect credentials from exposure at rest, in transit, and in use.
Common Credential Types in ASP.NET Core Web API
Database Connection Strings (SQL Server, PostgreSQL, etc.)
API Keys & Tokens (for external services like Stripe, SendGrid, or AWS)
User Passwords (stored and validated for authentication)
Certificates & Encryption Keys
Cloud Secrets (Azure, AWS, GCP credentials)
🛠Best Practices for Credential Security in ASP.NET Core Web API
1. Never Hardcode Credentials
Bad
public class DbContextExample : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=myServer;Database=myDb;User=myUser;Password=myPass;");
}
}
Good (use configuration providers)
public class DbContextExample : DbContext
{
private readonly IConfiguration _config;
public DbContextExample(IConfiguration config)
{
_config = config;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _config.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString);
}
}
2. Use appsettings.json + User Secrets
Store connection strings and credentials in the appsettings.json file.
For development, use Secret Manager to avoid committing secrets to Git.
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=SecureDB;Trusted_Connection=True;"
},
"ApiKeys": {
"SendGrid": "your-api-key"
}
}
Store secrets securely in development.
dotnet user-secrets set "ApiKeys:SendGrid" "super-secret-key"
Access in code.
var apiKey = _config["ApiKeys:SendGrid"];
3. Secure Production Secrets with Azure Key Vault
Instead of storing secrets locally, integrate Azure Key Vault.
Startup.cs / Program.cs.
builder.Configuration.AddAzureKeyVault(
new Uri("https://my-keyvault.vault.azure.net/"),
new DefaultAzureCredential());
Now, retrieve secrets.
string dbPassword = builder.Configuration["DbPassword"];
4. Hash & Salt User Passwords
Passwords should never be stored in plain text.
Use ASP.NET Core Identity or PasswordHasher<T>.
var hasher = new PasswordHasher<string>();
string hashedPassword = hasher.HashPassword(null, "MySecurePassword123!");
Verification
var result = hasher.VerifyHashedPassword(null, hashedPassword, "MySecurePassword123!");
if (result == PasswordVerificationResult.Success)
{
// Authenticated
}
5. Use HTTPS Everywhere
app.UseHttpsRedirection();
6. Protect API Keys
For APIs that require API key authentication.
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string API_KEY_HEADER = "X-API-KEY";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IConfiguration config)
{
if (!context.Request.Headers.TryGetValue(API_KEY_HEADER, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key missing");
return;
}
var apiKey = config["ApiKeys:MyService"];
if (!apiKey.Equals(extractedApiKey))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Unauthorized client");
return;
}
await _next(context);
}
}
Register in the Program.cs.
app.UseMiddleware<ApiKeyMiddleware>();
7. Use Managed Identities for Cloud Resources
Instead of storing Azure credentials, assign a managed identity to your API.
The API authenticates to Azure resources without storing secrets.
8. Enable Logging & Monitoring
_logger.LogWarning("Failed login attempt for user {User}", username);
Summary
Credential security in ASP.NET Core Web API revolves around protecting secrets at all stages.
Development: Use Secret Manager.
Production: Use Azure Key Vault / AWS Secrets Manager.
Passwords: Always hash and salt.
API Keys: Validate securely in middleware.
Transport Security: Always enforce HTTPS.
Cloud Resources: Use Managed Identities.
By applying these best practices, your APIs remain secure, compliant, and resilient against common attacks such as credential theft, replay attacks, and source code leaks.