Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
138 lines (119 loc) · 4.31 KB
/
Copy pathProgram.cs
File metadata and controls
138 lines (119 loc) · 4.31 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
using SmartTaskTracker.API.Data;
using Microsoft.EntityFrameworkCore;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Azure Key Vault Integration (only if configured)
if(builder.Environment.IsDevelopment())
{
builder.Configuration.AddUserSecrets<Program>();
}
else
{
var keyVaultName = builder.Configuration["KeyVaultName"];
if (!string.IsNullOrEmpty(keyVaultName))
{
var keyVaultUri = new Uri($"https://{keyVaultName}.vault.azure.net/");
builder.Configuration.AddAzureKeyVault(keyVaultUri, new DefaultAzureCredential());
}
}
// JWT Authentication Setup
var jwtKey = builder.Configuration["Jwt:Key"];
var jwtIssuer = builder.Configuration["Jwt:Issuer"];
var jwtAudience = builder.Configuration["Jwt:Audience"];
if (string.IsNullOrEmpty(jwtKey))
{
throw new InvalidOperationException("JWT Key is not configured. Please set it via User Secrets or Environment Variables.");
}
var key = Encoding.UTF8.GetBytes(jwtKey);
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 = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
// Authorization Policy Setup
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
options.AddPolicy("ManagerOnly", policy => policy.RequireRole("Manager"));
options.AddPolicy("DeveloperOnly", policy => policy.RequireRole("Developer"));
options.AddPolicy("AdminOrManager", policy => policy.RequireRole("Admin", "Manager"));
options.AddPolicy("ManagerOrDeveloper", policy => policy.RequireRole("Manager","Developer"));
options.AddPolicy("AllRoles", policy => policy.RequireRole("Admin", "Developer", "Manager"));
});
// Add services to the container
builder.Services.AddOpenApi();
// CORS Configuration
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAngular", policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// ✅ FIXED: Database Context - Properly read connection string
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
if (string.IsNullOrEmpty(connectionString))
{
// Fallback: read directly from environment variable
connectionString = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
}
if (string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Database connection string 'DefaultConnection' is not configured!");
}
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connectionString));
// JSON Serialization Configuration
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Disable caching middleware
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/api"))
{
context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
context.Response.Headers.Append("Pragma", "no-cache");
context.Response.Headers.Append("Expires", "0");
}
await next();
});
// Enable Swagger in Production
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Smart Task Tracker API v1");
c.RoutePrefix = "swagger";
});
// Middleware order
app.UseCors("AllowAngular");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();