-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
152 lines (128 loc) · 4.91 KB
/
Program.cs
File metadata and controls
152 lines (128 loc) · 4.91 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
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using appsec_assignment_2.Data;
using appsec_assignment_2.Models;
using appsec_assignment_2.Services;
using appsec_assignment_2.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add DbContext
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Identity
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// Password requirements (min 12 chars, lowercase, uppercase, digit, special char)
options.Password.RequiredLength = 12;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredUniqueChars = 1;
// Lockout settings (3 failed attempts, 15 min lockout)
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(5);
options.Lockout.MaxFailedAccessAttempts = 3;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
// Sign-in settings
options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddPasswordValidator<PasswordHistoryValidator>();
// Configure application cookie
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
options.AccessDeniedPath = "/Errors/403";
});
// Add session support
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
builder.Services.Configure<EmailOptions>(
builder.Configuration.GetSection(EmailOptions.SectionName));
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.Configure<BackupOptions>(
builder.Configuration.GetSection(BackupOptions.SectionName));
builder.Services.AddScoped<EncryptionService>();
builder.Services.AddScoped<DatabaseBackupService>();
builder.Services.AddHostedService<BackupHostedService>();
builder.Services.AddScoped<AuditService>();
builder.Services.AddScoped<RecaptchaService>();
builder.Services.AddHttpClient<RecaptchaService>();
builder.Services.AddRazorPages();
builder.Services.AddAntiforgery(options =>
{
options.FormFieldName = "__RequestVerificationToken";
options.HeaderName = "RequestVerificationToken";
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.HttpOnly = true;
});
var app = builder.Build();
if (args.Contains("--backup"))
{
using var scope = app.Services.CreateScope();
var backupService = scope.ServiceProvider.GetRequiredService<DatabaseBackupService>();
var (success, _) = await backupService.CreateBackupAsync();
Environment.Exit(success ? 0 : 1);
}
using (var scope = app.Services.CreateScope())
{
try
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.EnsureCreated();
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetService<ILogger<Program>>();
logger?.LogError(ex, "Database initialization failed");
}
}
app.UseExceptionHandler("/Errors/500");
app.Use(async (context, next) =>
{
if (!context.Request.IsHttps)
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
await next();
});
app.UseHsts();
app.UseHttpsRedirection();
// Security headers
app.Use(async (context, next) =>
{
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
context.Response.Headers.Append("X-Frame-Options", "DENY");
context.Response.Headers.Append("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
context.Response.Headers.Append("Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline' https://www.google.com https://www.gstatic.com; " +
"frame-src https://www.google.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:;");
await next();
});
app.UseStatusCodePagesWithReExecute("/Errors/Error", "?code={0}");
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseSessionValidation();
app.MapStaticAssets();
app.MapRazorPages()
.WithStaticAssets();
app.Run();