-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
176 lines (151 loc) · 6.61 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
using Fonlow.AspNetCore.Identity;
using Fonlow.AspNetCore.Identity.EntityFrameworkCore;
using Fonlow.DateOnlyExtensions;
using Fonlow.EntityFrameworkCore;
using Fonlow.WebApp.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using WebApp.Utilities;
System.Reflection.Assembly appAssembly = System.Reflection.Assembly.GetExecutingAssembly();
string dirOfAppAssembly = System.IO.Path.GetDirectoryName(appAssembly.Location);
IConfigurationRoot config = new ConfigurationBuilder().AddJsonFile(System.IO.Path.Combine(dirOfAppAssembly, "appsettings.json")).Build();
var appSettings = config.GetSection("appSettings");
var environment = appSettings.GetValue<string>("environment");
var dbEngineDbContextPlugins = appSettings.GetSection("dbEngineDbContextPlugins").Get<string[]>();
var identityConnectionString = config.GetConnectionString("IdentityConnection");
IAuthSetupSecrets authSetupSettings = null;
IAuthSettings authSettings = null;
if (environment == "test")
{
var authSetupSettingsSection = config.GetSection("AuthSetupSettings");
var authSetupSettingsObject = new AuthSetupSettings();
authSetupSettingsSection.Bind(authSetupSettingsObject);
authSetupSettings = authSetupSettingsObject;
authSettings = authSetupSettingsObject;
}
else
{
// fill authSetupSettings with data from a secured storage
}
if (authSetupSettings == null || string.IsNullOrEmpty(authSetupSettings.SymmetricSecurityKeyString))
{
throw new ArgumentException("Need SymmetricSecurityKeyString"); // or throw whatever app specific exception
}
string webRootPath = "./";
string dataDirectory = "./DemoApp_Data";
// WebRootPath is to tell the Web server where to look for files to serve.
// ContentRootPath is to tell the Web service code where to look for data.
// On Windows, ContentRootPath is the starting folder of the app assembly, and on MacOS, it is the user profile folder like //Users/MyName.
// Thus on MacOS, the App_Data folder should be under the user profile folder.
var options = new WebApplicationOptions
{
WebRootPath = webRootPath,
Args = args,
};
var builder = WebApplication.CreateBuilder(options);
builder.Configuration.AddConfiguration(config);
Console.WriteLine($"Start at contentRootPath: {builder.Environment.ContentRootPath}; WebRootPath: {builder.Environment.WebRootPath}; Current: {Directory.GetCurrentDirectory()}");
var issuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(authSetupSettings.SymmetricSecurityKeyString));
builder.Services.AddSingleton(issuerSigningKey);
builder.Services.AddSingleton(authSettings);
builder.Services.AddControllers(configure =>
{
#if DEBUG
configure.Conventions.Add(new Fonlow.CodeDom.Web.ApiExplorerVisibilityEnabledConvention());//To make ApiExplorer be visible to WebApiClientGen
#endif
configure.ModelBinderProviders.Insert(0, new OAuth2RequestBinderProvider());
})
.AddJsonOptions(// as of .NET 7/8, could not handle JS/CS test cases getInt2D, postInt2D and PostDictionaryOfPeople, around 14 C# test cases fail.
options =>
{
});
builder.Services.AddAuthentication(
options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //Bearer
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}
).AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = authSettings.Audience,
ValidIssuer = authSettings.Issuer,
IssuerSigningKey = issuerSigningKey,
#if DEBUG
ClockSkew = TimeSpan.FromSeconds(2), //Default is 300 seconds. This is for testing the correctness of the auth protocol implementation between C/S.
#endif
}; // Thanks to https://dotnetdetail.net/asp-net-core-3-0-web-api-token-based-authentication-example-using-jwt-in-vs2019/
});
builder.Services.AddCors(options => options.AddPolicy("All", builder =>
{
builder.AllowAnyMethod()
.AllowAnyOrigin()
.AllowAnyHeader()
;
}));
var dbEngineDbContext = DbEngineDbContextLoader.CreateDbEngineDbContextFromAssemblyFile(dbEngineDbContextPlugins[0] + ".dll");
if (dbEngineDbContext == null)
{
Console.Error.WriteLine("No dbEngineDbContext");
throw new ArgumentException("Need dbEngineDbContextPlugin");
}
Console.WriteLine($"DB Engine: {dbEngineDbContext.DbEngineName}");
builder.Services.AddDbContext<ApplicationDbContext>(dcob =>
{
dbEngineDbContext.ConnectDatabase(dcob, identityConnectionString); // called by runtime everytime an instance of ApplicationDbContext is created.
});
builder.Services.AddIdentity<ApplicationUser, ApplicationIdentityRole>(
options =>
{
options.ClaimsIdentity.UserNameClaimType = "UserID";
}
)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserManager<ApplicationUserManager>()
.AddDefaultTokenProviders()
.AddTokenProvider(authSettings.TokenProviderName, typeof(DataProtectorTokenProvider<ApplicationUser>)); //thanks to https://stackoverflow.com/questions/53659247/using-aspnetusertokens-table-to-store-refresh-token-in-asp-net-core-web-api;
var app = builder.Build();
if (app.Environment.IsDevelopment()) //ASPNETCORE_ENVIRONMENT=Development in web.config
{
app.UseDeveloperExceptionPage();
}
else
{
// //Only release build support https redirection.
//#if RELEASE
// if (useHttps) // for locally running app, no need to have https.
// {
// app.UseHttpsRedirection();
// app.UseHsts();//https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-6.0
// }
//#endif
}
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("All");
app.MapControllers();
if (args.Length > 1)
{
app.Urls.Add(builder.Environment.WebRootPath);
}
app.UseStaticFiles(); //This may cause IIS rewrite rule to fail during login. So, not to use IIS Rewrite rule.
//and using rewrit in middleware is not worthy, https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-6.0
app.Run();
Console.WriteLine("Run Done.");