-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
181 lines (149 loc) · 5.98 KB
/
Copy pathProgram.cs
File metadata and controls
181 lines (149 loc) · 5.98 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
using AuthCenter.Data;
using AuthCenter.Handler;
using AuthCenter.HostServices;
using AuthCenter.ViewModels;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using StackExchange.Redis;
using System.Diagnostics;
using System.Linq;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AuthCenterDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("UserContext") ?? throw new InvalidOperationException("Connection string 'UserContext' not found."))
.UseSnakeCaseNamingConvention());
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("RedisContext");
options.InstanceName = "HuiPass";
});
// Add services to the container.
builder.Services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = UserRoleAuthorizationHandler.UserRoleSchemeName;
config.DefaultChallengeScheme = UserRoleAuthorizationHandler.UserRoleSchemeName;
config.AddScheme<UserRoleAuthorizationHandler>(UserRoleAuthorizationHandler.UserRoleSchemeName, UserRoleAuthorizationHandler.UserRoleSchemeName);
config.AddScheme<BasicAuthorizationHandler>(BasicAuthorizationHandler.BasicSchemeName, BasicAuthorizationHandler.BasicSchemeName);
config.AddScheme<BearerAuthorizationHandler>(BearerAuthorizationHandler.BearerSchemeName, BearerAuthorizationHandler.BearerSchemeName);
});
//builder.Services.AddAuthentication();
builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var error = new ValidationProblemDetails(context.ModelState);
return new JsonResult(JSONResult.ResponseError(error.Title?.ToString() ?? ""));
};
}).AddXmlDataContractSerializerFormatters().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});
var sessionName = $"{builder.Configuration.GetSection("ServerStrings")["ServerName"]?.Replace(" ", "")}.Session";
builder.Services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.Name = sessionName;
options.IdleTimeout = TimeSpan.FromDays(30);
options.Cookie.MaxAge = TimeSpan.FromDays(30);
options.Cookie.IsEssential = true;
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options => options.CustomSchemaIds(x => x.FullName));
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton(ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("RedisContext") ?? "").GetDatabase(0));
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddPolicy("login", httpContext =>
{
var sessionId = httpContext.Session.Id;
if (sessionId != null)
{
return RateLimitPartition.GetFixedWindowLimiter(sessionId,
partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1)
});
}
return RateLimitPartition.GetNoLimiter("");
});
options.AddPolicy("userVerify", httpContext =>
{
var userId = httpContext.User.Identity?.Name;
if (userId != null)
{
return RateLimitPartition.GetFixedWindowLimiter(userId,
partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 5,
Window = TimeSpan.FromMinutes(5)
});
}
return RateLimitPartition.GetNoLimiter("");
});
});
builder.Services.AddHostedService<CleanExpiredTokenService>();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AuthCenterDbContext>();
db.Database.Migrate();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
var currentDir = Directory.GetCurrentDirectory();
var baseDir = Path.Combine(currentDir, builder.Configuration["baseDir"] ?? "./upload");
if (!Directory.Exists(baseDir))
{
Directory.CreateDirectory(baseDir);
}
app.UseForwardedHeaders();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(baseDir),
RequestPath = "/api/static"
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.Use(async (context, next) =>
{
// Session Id will always change until first value is set
if (!context.Request.Cookies.TryGetValue(sessionName, out _))
{
context.Session.SetString("-", "");
}
var logger = context.RequestServices.GetService<ILoggerFactory>()?
.CreateLogger("PerformanceLog");
var profiler = new Stopwatch();
profiler.Start();
await next();
profiler.Stop();
logger?.LogInformation("TraceId:{TraceId}, RequestMethod:{RequestMethod}, RequestPath:{RequestPath}, ElapsedMilliseconds:{ElapsedMilliseconds}, Response StatusCode: {StatusCode}",
context.TraceIdentifier, context.Request.Method, context.Request.Path, profiler.ElapsedMilliseconds, context.Response.StatusCode);
});
app.UseRateLimiter();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.UseExceptionHandler(o => { });
app.Run();