-
Notifications
You must be signed in to change notification settings - Fork 24
/
Startup.cs
231 lines (195 loc) · 8.2 KB
/
Startup.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using ProtoBuf.Grpc.Server;
using HybridBlazor.Shared;
using HybridBlazor.Client;
using HybridBlazor.Server.Data;
using HybridBlazor.Server.Data.Models;
using HybridBlazor.Server.Services;
using Microsoft.AspNetCore.Hosting.Server.Features;
namespace HybridBlazor.Server
{
public class Startup
{
private IServerAddressesFeature serverAddressesFeature;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase(nameof(ApplicationDbContext)));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Lockout.AllowedForNewUsers = true;
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1);
options.User.RequireUniqueEmail = true;
});
services
.AddAuthentication(cfg =>
{
cfg.DefaultScheme = IdentityConstants.ApplicationScheme;
cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer()
.AddCookie();
services.Configure<HybridOptions>(Configuration);
services.AddControllersWithViews();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddGrpc(options =>
{
options.Interceptors.Add<GrpcExceptionInterceptor>();
options.ResponseCompressionAlgorithm = "gzip";
options.ResponseCompressionLevel = System.IO.Compression.CompressionLevel.Optimal;
options.EnableDetailedErrors = true;
});
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
services.AddCodeFirstGrpc(config =>
{
config.EnableDetailedErrors = true;
config.ResponseCompressionLevel = System.IO.Compression.CompressionLevel.Optimal;
});
services.AddHttpContextAccessor();
services.AddTransient(sp =>
{
var env = sp.GetService<IWebHostEnvironment>();
var httpContextAccessor = sp.GetService<IHttpContextAccessor>();
var httpContext = httpContextAccessor.HttpContext;
var cookies = httpContext.Request.Cookies;
var cookieContainer = new System.Net.CookieContainer();
foreach (var c in cookies)
{
cookieContainer.Add(new System.Net.Cookie(c.Key, c.Value) { Domain = httpContext.Request.Host.Host });
}
var handler = new HttpClientHandler { CookieContainer = cookieContainer };
if (env.IsDevelopment())
{
handler.ServerCertificateCustomValidationCallback = (c, v, b, n) => { return true; };
}
return handler;
});
services.AddTransient(sp =>
{
var handler = sp.GetService<HttpClientHandler>();
if (serverAddressesFeature?.Addresses == null
|| serverAddressesFeature.Addresses.Count == 0)
{
return new HttpClient(handler);
}
var insideIIS = Environment.GetEnvironmentVariable("APP_POOL_ID") is string;
var address = serverAddressesFeature.Addresses
.FirstOrDefault(a => a.StartsWith($"http{(insideIIS ? "s" : "")}:"))
?? serverAddressesFeature.Addresses.First();
var uri = new Uri(address);
return new HttpClient(handler) { BaseAddress = new Uri($"{uri.Scheme}://localhost:{uri.Port}") };
});
services.AddScoped<IAuthService, ServerAuthService>();
services.AddSingleton<CounterStateStorageService>();
Client.Program.ConfigureCommonServices(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();
UpdateDatabase<ApplicationDbContext>(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseResponseCompression();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
app.Use((context, next) =>
{
var idCookiaName = "hubrid-instance-id";
if (!context.Request.Cookies.Any(c => c.Key == idCookiaName))
{
var idCookieOptions = new CookieOptions
{
Path = "/",
Secure = true,
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Strict,
Expires = DateTime.Now.AddYears(100),
};
context.Response.Cookies.Append(
key: idCookiaName,
value: Guid.NewGuid().ToString(),
options: idCookieOptions);
}
return next();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<Services.WeatherForecastService>();
endpoints.MapGrpcService<Services.CounterService>();
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
private static void UpdateDatabase<T>(IApplicationBuilder app) where T : DbContext
{
using var scope = app.ApplicationServices.CreateScope();
var context = scope.ServiceProvider.GetService<T>();
context.Database.EnsureCreated();
}
}
public enum HybridType
{
ServerSide,
WebAssembly,
HybridManual,
HybridOnNavigation,
HybridOnReady
}
public class HybridOptions
{
public HybridType HybridType { get; set; }
}
}