-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
189 lines (161 loc) · 5.41 KB
/
Program.cs
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
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using TodoAppAPI.Models;
using TodoAppAPI.Services;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Configure thread pool
ThreadPool.SetMinThreads(100, 100);
// Add logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
builder.Services.AddCors(options =>
{
options.AddPolicy("DevelopmentPolicy", policy =>
policy.WithOrigins("http://localhost:4000",
"http://localhost:5163",
"http://127.0.0.1:5163")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
options.AddPolicy("ProductionPolicy", policy =>
policy.WithOrigins("https://3xjn.dev",
"https://www.3xjn.dev",
"http://3xjn.dev",
"http://www.3xjn.dev")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("local.appsettings.json", true, true)
.AddUserSecrets<Program>(optional: true)
.AddEnvironmentVariables()
.Build();
builder.Services.Configure<TodoDatabaseSettings>(
config.GetSection("Mongo"));
builder.Services.AddSingleton(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<TodoDatabaseSettings>>().Value;
Console.WriteLine($"Connecting to with string of {settings.ConnectionString.Length} length");
return new MongoClient(settings.ConnectionString);
});
builder.Services.AddScoped<TodoService>();
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "TodoApp API", Version = "v1" });
option.AddSecurityDefinition(
"Bearer",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
}
);
option.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
}
);
});
var environment = builder.Environment;
IdentityModelEventSource.ShowPII = true;
builder.Services.AddSingleton<RSA>(serviceProvider =>
{
var publicKey = config["Jwt:PublicKey"];
if (string.IsNullOrEmpty(publicKey))
{
throw new InvalidOperationException("JWT public key is not configured.");
}
var rsa = RSA.Create();
rsa.ImportFromPem(publicKey);
return rsa;
});
builder.Services.AddSingleton(serviceProvider =>
{
var rsa = serviceProvider.GetRequiredService<RSA>();
return new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuers = new[] { "https://accounts.google.com", "https://3xjn.dev" },
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new RsaSecurityKey(rsa),
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true
};
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://accounts.google.com";
options.Audience = config["Authentication:Google:ClientId"];
options.TokenValidationParameters = builder.Services.BuildServiceProvider()
.GetRequiredService<TokenValidationParameters>();
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Authentication failed: {context.Exception}");
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token validated successfully.");
return Task.CompletedTask;
}
};
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseCors("DevelopmentPolicy");
app.UseSwagger();
app.UseSwaggerUI();
IdentityModelEventSource.ShowPII = true;
} else
{
app.UseCors("ProductionPolicy");
}
app.UseAuthentication();
app.UseAuthorization();
var defaultFilesOptions = new DefaultFilesOptions();
var staticFileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.WebRootPath, "app"));
app.UseDefaultFiles(new DefaultFilesOptions
{
FileProvider = staticFileProvider
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = staticFileProvider
});
app.MapControllers();
app.Run();