A secure ASP.NET Core web application for managing sensitive data including user credentials and financial records with comprehensive authentication and authorization.
β ASP.NET Core Identity Integration
- Modern, secure authentication framework
- Email-based user verification
- Password reset functionality
- Two-factor authentication (2FA) support
- Account lockout after 5 failed attempts (15-minute lockout)
β Role-Based Authorization (RBAC)
- Admin role - Full system access and user management
- User role - Manage own financial records
- Guest role - Read-only access
- Fine-grained permission control
β Claims-Based Authorization
CanManageFinancials- Permission to create/update/delete financial recordsCanViewReports- Permission to view financial reportsCanManageUsers- Permission to manage other users (admin only)
β Resource-Based Authorization
- Users can only access their own financial records
- Admins have access to all records
- Custom authorization handlers for financial data
β Input Validation
- Custom validation attributes for SQL injection prevention
- XSS attack prevention validators
- Data annotations on all models
- Both client-side and server-side validation
β SQL Injection Prevention
- Entity Framework Core with parameterized queries
- No raw SQL concatenation
- Secure query practices throughout
β XSS Prevention
- Automatic output encoding in Razor views
- Content Security Policy (CSP) headers
- Input sanitization validators
β Password Security
- ASP.NET Core Identity password hashing (PBKDF2 with HMAC-SHA256)
- BCrypt password hashing also available (work factor: 12)
- Strong password requirements (8+ chars, uppercase, lowercase, number, special char)
- Account lockout after 5 failed login attempts (15-minute lockout)
- Password history and complexity enforcement
β Data Encryption
- AES-256 encryption for financial records
- Random IV generation for each encryption operation
- Encrypted sensitive data at rest
- Secure key management (no hardcoded keys)
- IV prepended to ciphertext for secure decryption
β Security Headers
- Content-Security-Policy
- X-Frame-Options (DENY)
- X-Content-Type-Options (nosniff)
- X-XSS-Protection
- Referrer-Policy
- Permissions-Policy
β Additional Security
- HTTPS enforcement
- Anti-forgery tokens on all forms
- Secure session management
- HttpOnly and Secure cookie flags
- Framework: ASP.NET Core 8.0
- Authentication: ASP.NET Core Identity 8.0
- ORM: Entity Framework Core 8.0
- Database: SQLite (easily switchable to SQL Server)
- Testing: NUnit 3
- Password Hashing: ASP.NET Core Identity (PBKDF2), BCrypt.Net-Next
- Encryption: AES-256 (System.Security.Cryptography)
SafeVault/
βββ SafeVault.Web/ # Main web application
β βββ Controllers/ # MVC controllers
β β βββ UserController.cs # User registration/login/2FA
β β βββ FinancialController.cs # Financial records CRUD
β β βββ AdminController.cs # User management (Admin only)
β β βββ HomeController.cs
β βββ Models/ # Data models
β β βββ ApplicationUser.cs # Identity user model
β β βββ User.cs # Legacy user model
β β βββ UserCredential.cs # Legacy credentials
β β βββ FinancialRecord.cs
β β βββ ViewModels.cs
β β βββ AccountViewModels.cs # Account management models
β βββ Data/ # Database context
β β βββ SafeVaultDbContext.cs
β β βββ DbInitializer.cs # Role and admin seeding
β βββ Services/ # Business logic
β β βββ EncryptionService.cs
β β βββ PasswordHasher.cs
β β βββ EmailSender.cs # Email notifications
β βββ Authorization/ # Authorization policies
β β βββ Requirements.cs
β β βββ FinancialRecordAuthorizationHandler.cs
β βββ Validators/ # Custom validators
β β βββ SecurityValidators.cs
β βββ Views/ # Razor views
β βββ User/ # Login, Register, 2FA
β βββ Financial/ # Financial records
β βββ Admin/ # Admin panel
βββ SafeVault.Tests/ # NUnit test project
βββ TestInputValidation.cs
βββ TestPasswordHashing.cs
βββ TestEncryption.cs
βββ TestDatabaseSecurity.cs
βββ TestAuthorization.cs # Authorization tests
- .NET 8.0 SDK or later
- Any IDE that supports .NET (Visual Studio, VS Code, Rider)
- Clone the repository:
git clone https://github.com/jrigo23/SafeVault.git
cd SafeVault- Build the solution:
dotnet build- Run the tests:
dotnet test- Run the web application:
cd SafeVault.Web
dotnet run- Navigate to
https://localhost:5001in your browser
The application uses SQLite by default with the database file created at SafeVault.Web/safevault.db.
On first run, a default admin account is created:
- Username: admin
- Email: admin@safevault.com
- Password: Admin@123456
To switch to SQL Server, update the connection string in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=SafeVault;Trusted_Connection=True;"
}And update Program.cs to use SQL Server:
builder.Services.AddDbContext<SafeVaultDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));- Registration: Secure user registration with email confirmation required
- Email Confirmation: Token-based email verification before first login
- Login: Multi-factor authentication with account lockout protection
- Password Reset: Secure password reset workflow via email
- Two-Factor Authentication (2FA): Optional email-based 2FA for enhanced security
- Session Management: Secure cookie-based authentication with sliding expiration
- Role-Based Access: Admin, User, and Guest roles with different permissions
- Claims-Based Policies: Fine-grained permissions for specific operations
- Resource-Based Authorization: Users can only access their own data (except Admins)
- Admin Panel: User management, role assignment, account locking/unlocking
- Create: Add new financial records with encrypted sensitive data
- Read: View financial records (decrypted for authorized users)
- Search: Search records by description (SQL injection safe)
- Delete: Remove records with confirmation
The application includes comprehensive security tests covering all critical security aspects:
Located in SafeVault.Tests/TestInputValidation.cs:
- TestForSQLInjection_DetectsSQLKeywords - Validates detection of SQL injection attempts including
' or '1'='1,DROP TABLE,UNION SELECT, and SQL comments - TestForSQLInjection_AllowsValidInput - Ensures legitimate input like usernames, emails, and product names are accepted
- TestForXSS_DetectsScriptTags - Detects XSS attacks including
<script>tags,javascript:protocol, event handlers, and data URIs - TestForXSS_AllowsValidInput - Allows safe text input without HTML/JavaScript
- TestNoMaliciousInput_DetectsDangerousCharacters - Identifies dangerous characters like
<>, quotes, and SQL comment sequences - TestNoMaliciousInput_AllowsCleanInput - Permits clean alphanumeric input with standard punctuation
- TestSQLInjection_CommonBypassAttempts - Tests against advanced SQL injection bypass techniques including
UNION ALL SELECTand comment-based attacks - TestXSS_EventHandlerInjection - Validates detection of XSS via event handlers (
onerror,onload,onclick,onmouseover,onfocus)
Located in SafeVault.Tests/TestPasswordHashing.cs:
- HashPassword_CreatesNonEmptyHash - Verifies BCrypt hash generation produces non-empty strings with proper length
- HashPassword_CreatesDifferentHashesForSamePassword - Confirms salting creates unique hashes for identical passwords
- VerifyPassword_ReturnsTrueForCorrectPassword - Validates correct password verification
- VerifyPassword_ReturnsFalseForIncorrectPassword - Ensures incorrect passwords are rejected
- VerifyPassword_ReturnsFalseForEmptyPassword - Rejects empty password attempts
- HashPassword_ThrowsExceptionForEmptyPassword - Prevents hashing of empty passwords
- HashPassword_WorksWithSpecialCharacters - Handles special characters in passwords (
!@#$%^&*()) - HashPassword_WorksWithLongPasswords - Supports long password strings (50+ characters)
Located in SafeVault.Tests/TestEncryption.cs:
- Encrypt_CreatesNonEmptyEncryptedString - Verifies AES-256 encryption produces non-empty ciphertext different from plaintext
- Decrypt_ReturnsOriginalPlainText - Validates encryption/decryption round-trip accuracy
- Encrypt_HandlesEmptyString - Properly handles empty string encryption/decryption
- Encrypt_WorksWithSpecialCharacters - Encrypts/decrypts special characters correctly
- Encrypt_WorksWithNumbers - Handles numeric strings
- Encrypt_WorksWithLongStrings - Successfully encrypts strings up to 1000+ characters
- Encrypt_ProducesDifferentOutputForDifferentInput - Different plaintext produces different ciphertext
- Encrypt_ProducesDifferentOutputForSameInput - Random IV ensures same plaintext produces different ciphertext each time
- Encrypt_DataIsNotStoredInPlainText - Confirms encrypted data doesn't contain plaintext fragments
Located in SafeVault.Tests/TestDatabaseSecurity.cs:
- SQLInjection_PreventedByParameterizedQueries - Verifies EF Core's parameterized queries block SQL injection attempts
- SQLInjection_DropTableAttemptFails - Confirms
DROP TABLEinjection attempts fail and tables remain intact - PasswordsAreHashedNotPlainText - Validates passwords are stored as BCrypt hashes, not plaintext
- FinancialData_IsEncryptedAtRest - Ensures sensitive financial data is encrypted in the database
- UnionSelectInjectionAttempt_IsBlocked - Blocks
UNION SELECTinjection attempts in search queries - UserDataIsolation_PreventsUnauthorizedAccess - Enforces user data isolation (users can't access other users' records)
- CascadeDelete_RemovesRelatedData - Verifies cascade deletion removes related credentials when user is deleted
Located in SafeVault.Tests/TestAuthorization.cs:
- RoleCreation_SuccessfullyCreatesRole - Tests ASP.NET Core Identity role creation
- UserRoleAssignment_SuccessfullyAssignsRole - Validates user-to-role assignment functionality
- UserClaims_SuccessfullyAddsClaims - Confirms claims-based authorization (
CanManageFinancials,CanViewReports) - MultipleRoles_UserCanHaveMultipleRoles - Verifies users can be assigned multiple roles simultaneously
- RoleRemoval_SuccessfullyRemovesRole - Tests role removal from users
- PasswordValidation_EnforcesPasswordPolicy - Ensures weak passwords are rejected (short, no complexity)
- PasswordValidation_AcceptsStrongPassword - Accepts passwords meeting complexity requirements
- EmailConfirmation_RequiredForLogin - Validates email confirmation workflow
- TwoFactorAuthentication_CanBeEnabled - Tests 2FA enablement for users
Total: 41 tests - All passing! β
# Run all tests
dotnet test
# Run with detailed output
dotnet test --verbosity normal
# Run specific test class
dotnet test --filter "ClassName=TestInputValidation"The application requires an encryption key to be configured. The key must be at least 32 characters long.
For Development:
The key is pre-configured in appsettings.Development.json for local development only.
For Production:
- Remove the example key from development settings
- Store encryption keys in a secure location:
- Azure Key Vault
- AWS Secrets Manager
- Environment variables
- Secure configuration provider
- HashiCorp Vault
Setting via Environment Variable:
# Linux/macOS
export Encryption__Key="Your32+CharacterProductionKeyHere"
# Windows
set Encryption__Key=Your32+CharacterProductionKeyHereImportant: The application will fail to start if no valid encryption key is configured - this is intentional for security.
This application uses AES-256 encryption with the following security features:
- Random IV Generation: Each encryption operation generates a unique initialization vector (IV)
- IV Storage: The IV is prepended to the ciphertext for decryption
- No Static IVs: Ensures no patterns can be detected in encrypted data
- Secure Key Management: Keys are never hardcoded in production code
Security headers are configured in Program.cs:
app.Use(async (context, next) =>
{
context.Response.Headers.Append("Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'; ...");
// ... other headers
await next();
});This application follows OWASP Top 10 security guidelines:
- β Injection - Parameterized queries, input validation
- β Broken Authentication - Secure password hashing, account lockout
- β Sensitive Data Exposure - Encryption at rest, HTTPS
- β XML External Entities (XXE) - Not applicable (no XML processing)
- β Broken Access Control - User data isolation, session validation
- β Security Misconfiguration - Secure headers, HTTPS enforcement
- β Cross-Site Scripting (XSS) - Output encoding, CSP headers
- β Insecure Deserialization - Not applicable
- β Using Components with Known Vulnerabilities - Latest packages
- β Insufficient Logging & Monitoring - Logging implemented
This project is for educational and demonstration purposes.
This is a demonstration project showcasing secure coding practices in ASP.NET Core.