-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
322 lines (287 loc) · 13 KB
/
Copy pathProgram.cs
File metadata and controls
322 lines (287 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System.Data.Common;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using AuthServer.Data;
using AuthServer.Middleware;
using AuthServer.Models;
using AuthServer.Services;
using AuthServer.Config;
using AuthServer.DTOs;
using Serilog;
using AspNetCoreRateLimit;
// Configure Serilog with data protection
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/authserver-.txt", rollingInterval: RollingInterval.Day)
.Destructure.ByTransforming<LoginRequest>(r => new { r.Email, Password = "[PROTECTED]" })
.Destructure.ByTransforming<RegisterRequest>(r => new { r.Email, r.FirstName, r.LastName, Password = "[PROTECTED]" })
.Destructure.ByTransforming<ResetPasswordRequest>(r => new { r.Email, Token = "[PROTECTED]", NewPassword = "[PROTECTED]" })
.Destructure.ByTransforming<AppEmailConfig>(c => new { c.AppId, c.FromEmail, c.SmtpHost, c.SmtpPort, SmtpPassword = "[PROTECTED]" })
.CreateLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
// Add Serilog
builder.Host.UseSerilog();
// Database
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
Console.WriteLine($"DEBUG: Connection String = '{connectionString}'");
if (string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured or is empty.");
}
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
// Identity
// Configure Data Protection for cookies to persist across requests
builder.Services.AddDataProtection()
.SetApplicationName("AuthServer");
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.SignIn.RequireConfirmedEmail = true;
options.User.RequireUniqueEmail = true;
// Account lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// JWT Authentication
var jwtSecret = builder.Configuration["Jwt:Secret"];
if (string.IsNullOrEmpty(jwtSecret))
{
throw new InvalidOperationException("JWT Secret is not configured. Please set Jwt:Secret in appsettings.json");
}
if (jwtSecret.Length < 32)
{
throw new InvalidOperationException("JWT Secret must be at least 32 characters long for security.");
}
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret!)),
ClockSkew = TimeSpan.Zero
};
})
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Authentication:Google:ClientId"]
?? throw new InvalidOperationException("Google ClientId not configured");
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]
?? throw new InvalidOperationException("Google ClientSecret not configured");
options.CallbackPath = "/api/auth/google-callback";
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.CorrelationCookie.SameSite = SameSiteMode.Lax;
options.CorrelationCookie.SecurePolicy = builder.Environment.IsDevelopment()
? CookieSecurePolicy.None
: CookieSecurePolicy.Always;
options.CorrelationCookie.IsEssential = true;
options.CorrelationCookie.HttpOnly = true;
// Configure backchannel for OAuth token exchange
// Fix SSL connection issues in development
if (builder.Environment.IsDevelopment())
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
options.BackchannelHttpHandler = handler;
}
options.BackchannelTimeout = TimeSpan.FromSeconds(60);
// Intercept after authentication to preserve the returnUrl
options.Events.OnTicketReceived = context =>
{
// The returnUrl is already in properties.Items from GoogleLogin
// We just need to ensure it gets passed through
return Task.CompletedTask;
};
});
// Rate Limiting
builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
// CORS - Production-ready with strict origin validation
var allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>()
?? new[] { "http://localhost:3000", "http://localhost:5173" }; // Secure default for dev
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins", policy =>
{
// SECURITY: Never use "*" wildcard in production
if (allowedOrigins.Contains("*") && !builder.Environment.IsProduction())
{
// Only allow wildcard in development
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}
else
{
// Production: explicit origins only
var validOrigins = allowedOrigins.Where(o => o != "*").ToArray();
policy.WithOrigins(validOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}
});
});
// Anti-forgery for CSRF protection
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
// Services
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
builder.Services.AddScoped<IExternalAuthService, ExternalAuthService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<IUserActivityService, UserActivityService>();
builder.Services.AddSingleton<IEncryptionService, EncryptionService>();
builder.Services.AddSingleton<IPasswordHashingService, PasswordHashingService>();
builder.Services.AddScoped<ISecurityAuditService, SecurityAuditService>();
builder.Services.AddHostedService<TokenCleanupService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerConfiguration();
// Configure routing to be case-insensitive (fixes OAuth callback path issues)
builder.Services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = false;
});
var app = builder.Build();
// Seed roles and admin user
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roles = new[] { "Admin", "User", "Moderator" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
var result = await roleManager.CreateAsync(new IdentityRole(role));
if (!result.Succeeded)
{
Log.Error("Failed to create role {Role}: {Errors}", role, string.Join(", ", result.Errors.Select(e => e.Description)));
throw new InvalidOperationException($"Failed to create role {role}");
}
Log.Information("Created role: {Role}", role);
}
}
// Create default admin user
var adminEmail = "admin@authserver.com";
var adminUser = await userManager.FindByEmailAsync(adminEmail);
if (adminUser == null)
{
// SECURITY: Generate strong random password for initial admin
var adminPassword = builder.Configuration["AdminPassword"];
if (string.IsNullOrEmpty(adminPassword))
{
// Generate cryptographically secure random password if not configured
adminPassword = GenerateSecurePassword();
Log.Warning("SECURITY: No AdminPassword configured. A random password has been generated.");
Console.WriteLine("═══════════════════════════════════════════════════════════");
Console.WriteLine(" IMPORTANT: Generated Admin Password");
Console.WriteLine($" Password: {adminPassword}");
Console.WriteLine(" Please save this password securely and change it after first login!");
Console.WriteLine("═══════════════════════════════════════════════════════════");
}
adminUser = new ApplicationUser
{
UserName = adminEmail,
Email = adminEmail,
EmailConfirmed = true,
FirstName = "Admin",
LastName = "User"
};
var createResult = await userManager.CreateAsync(adminUser, adminPassword);
if (!createResult.Succeeded)
{
Log.Error("Failed to create admin user: {Errors}", string.Join(", ", createResult.Errors.Select(e => e.Description)));
throw new InvalidOperationException("Failed to create admin user");
}
var roleResult = await userManager.AddToRoleAsync(adminUser, "Admin");
if (!roleResult.Succeeded)
{
Log.Error("Failed to assign Admin role: {Errors}", string.Join(", ", roleResult.Errors.Select(e => e.Description)));
throw new InvalidOperationException("Failed to assign Admin role to admin user");
}
Log.Information("Default admin user created successfully: {Email}", adminEmail);
}
}
// Helper function to generate secure password
static string GenerateSecurePassword()
{
const string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@#$%^&*";
using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
var bytes = new byte[20];
rng.GetBytes(bytes);
return new string(bytes.Select(b => validChars[b % validChars.Length]).ToArray());
}
// Middleware Pipeline
app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseMiddleware<SecurityMonitoringMiddleware>();
app.UseMiddleware<GlobalExceptionHandler>();
// SECURITY: Only enable Swagger in development
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseSerilogRequestLogging();
app.UseIpRateLimiting();
app.UseCors("AllowSpecificOrigins");
app.UseAuthentication();
app.UseMiddleware<TokenBlacklistMiddleware>();
app.UseAuthorization();
app.MapControllers();
Log.Information("Authentication Server starting...");
app.Run();
}
catch (InvalidOperationException ex)
{
Log.Fatal(ex, "Configuration error during application startup: {Message}", ex.Message);
throw;
}
catch (DbException ex)
{
Log.Fatal(ex, "Database connection error during application startup");
throw;
}
catch (Exception ex)
{
Log.Fatal(ex, "Unexpected error during application start-up");
throw;
}
finally
{
Log.CloseAndFlush();
}