Storing sensitive data such as API keys, database passwords, or encryption secrets directly in code or config files is risky. Using secure configuration methods reduces exposure, protects your application, and prevents leaks.
ASP.NET allows you to use User Secrets for development and environment variables for production.
// Using Microsoft.Extensions.Configuration
using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add User Secrets for development to keep sensitive data out of source control
builder.Configuration.AddUserSecrets<Program>();
var app = builder.Build();
// Retrieve the secret value from configuration
var secretValue = app.Configuration["MySecret"];
Console.WriteLine(secretValue); // Prints the secret to console (for demo purposes only)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
// Inject the secret from application.properties or environment
@Value("${my.secret}")
private String secret;
public void printSecret() {
System.out.println(secret); // Print the secret value
}
}
require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const app = express();
console.log(process.env.MY_SECRET); // Access your secret safely via environment variables
app.listen(3000, () => console.log('Server running'));
export default function Home() {
return (
<div>
{/* Access public environment variable in Next.js */}
<p>Secret: {process.env.NEXT_PUBLIC_MY_SECRET}</p>
</div>
)
}
from flask import Flask
import os
app = Flask(__name__)
# Access secret from environment variables
secret = os.getenv('MY_SECRET')
print(secret) # Print secret for demo purposes
return [
// Retrieve secret from .env file safely
'secret' => env('MY_SECRET', 'default_value'),
];
Securing sensitive data in configuration is critical to prevent accidental leaks and protect your application. Ignoring this can lead to compromised secrets, unauthorized access, and potential legal implications. By using proper configuration methods like User Secrets, environment variables, or secure vaults, developers ensure safer and more maintainable applications.