-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathStartup.cs
290 lines (250 loc) · 11.8 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using IdentityServer4.Services;
using StsServerIdentity.Models;
using StsServerIdentity.Data;
using StsServerIdentity.Resources;
using StsServerIdentity.Services;
using StsServerIdentity.Filters;
using StsServerIdentity.Services.Certificate;
using Serilog;
using Microsoft.AspNetCore.Http;
using Fido2NetLib;
namespace StsServerIdentity;
public class Startup
{
private IConfiguration _configuration { get; }
private IWebHostEnvironment _environment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
_configuration = configuration;
_environment = env;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<StsConfig>(_configuration.GetSection("StsConfig"));
services.Configure<EmailSettings>(_configuration.GetSection("EmailSettings"));
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
options.OnAppendCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
var x509Certificate2Certs = GetCertificates(_environment, _configuration)
.GetAwaiter().GetResult();
AddLocalizationConfigurations(services);
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(_configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddErrorDescriber<StsIdentityErrorDescriber>()
.AddDefaultTokenProviders()
.AddTokenProvider<Fifo2UserTwoFactorTokenProvider>("FIDO2");
services.AddAuthentication()
.AddOpenIdConnect("aad", "Login with Azure AD", options => // Microsoft common
{
// https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
options.ClientId = "your_client_id"; // ADD APP Registration ID
options.ClientSecret = "your_secret"; // ADD APP Registration secret
options.SignInScheme = "Identity.External";
options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
options.Authority = "https://login.microsoftonline.com/common/v2.0/";
options.ResponseType = "code";
options.UsePkce = false; // live does not support this yet
options.Scope.Add("profile");
options.Scope.Add("email");
options.TokenValidationParameters = new TokenValidationParameters
{
// ALWAYS VALIDATE THE ISSUER IF POSSIBLE !!!!
ValidateIssuer = false,
// ValidIssuers = new List<string> { "tenant..." },
NameClaimType = "email",
};
options.CallbackPath = "/signin-microsoft";
options.Prompt = "login"; // login, consent
});
services.AddAntiforgery(options =>
{
options.SuppressXFrameOptionsHeader = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
services.AddControllersWithViews(options =>
{
options.Filters.Add(new SecurityHeadersAttribute());
})
.AddViewLocalization()
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
return factory.Create("SharedResource", assemblyName.Name);
};
})
.AddNewtonsoftJson();
var stsConfig = _configuration.GetSection("StsConfig");
var identityServer = services.AddIdentityServer()
.AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryApiScopes(Config.GetApiScopes())
.AddInMemoryClients(Config.GetClients(stsConfig))
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();
if (x509Certificate2Certs.SecondaryCertificate != null)
{
identityServer.AddValidationKey(x509Certificate2Certs.SecondaryCertificate);
}
services.Configure<Fido2Configuration>(_configuration.GetSection("fido2"));
services.AddScoped<Fido2Storage>();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(2);
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSecurityHeaders(
SecurityHeadersDefinitions.GetHeaderPolicyCollection(env.IsDevelopment()));
app.UseCookiePolicy();
if (_environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
// https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
// https://nblumhardt.com/2019/10/serilog-mvc-logging/
app.UseSerilogRequestLogging();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
private static async Task<(X509Certificate2 ActiveCertificate, X509Certificate2 SecondaryCertificate)> GetCertificates(IWebHostEnvironment environment, IConfiguration configuration)
{
var certificateConfiguration = new CertificateConfiguration
{
// Use an Azure key vault
CertificateNameKeyVault = configuration["CertificateNameKeyVault"], //"StsCert",
KeyVaultEndpoint = configuration["AzureKeyVaultEndpoint"], // "https://damienbod.vault.azure.net"
// Use a local store with thumbprint
//UseLocalCertStore = Convert.ToBoolean(configuration["UseLocalCertStore"]),
//CertificateThumbprint = configuration["CertificateThumbprint"],
// development certificate
DevelopmentCertificatePfx = Path.Combine(environment.ContentRootPath, "sts_dev_cert.pfx"),
DevelopmentCertificatePassword = "1234" //configuration["DevelopmentCertificatePassword"] //"1234",
};
(X509Certificate2 ActiveCertificate, X509Certificate2 SecondaryCertificate) certs = await CertificateService.GetCertificates(
certificateConfiguration).ConfigureAwait(false);
return certs;
}
private static void AddLocalizationConfigurations(IServiceCollection services)
{
services.AddSingleton<LocService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
new CultureInfo("de-CH"),
new CultureInfo("it-IT"),
new CultureInfo("gsw-CH"),
new CultureInfo("fr-FR"),
new CultureInfo("zh-Hans"),
new CultureInfo("ga-IE"),
new CultureInfo("es-MX")
};
options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
var providerQuery = new LocalizationQueryProvider
{
QueryParameterName = "ui_locales"
};
options.RequestCultureProviders.Insert(0, providerQuery);
});
}
private static void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
if (options.SameSite == SameSiteMode.None)
{
var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
if (DisallowsSameSiteNone(userAgent))
{
// For .NET Core < 3.1 set SameSite = (SameSiteMode)(-1)
options.SameSite = SameSiteMode.Unspecified;
}
}
}
private static bool DisallowsSameSiteNone(string userAgent)
{
// Cover all iOS based browsers here. This includes:
// - Safari on iOS 12 for iPhone, iPod Touch, iPad
// - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
// - Chrome on iOS 12 for iPhone, iPod Touch, iPad
// All of which are broken by SameSite=None, because they use the iOS networking stack
if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12"))
{
return true;
}
// Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:
// - Safari on Mac OS X.
// This does not include:
// - Chrome on Mac OS X
// Because they do not use the Mac OS networking stack.
if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") &&
userAgent.Contains("Version/") && userAgent.Contains("Safari"))
{
return true;
}
// Cover Chrome 50-69, because some versions are broken by SameSite=None,
// and none in this range require it.
// Note: this covers some pre-Chromium Edge versions,
// but pre-Chromium Edge does not require SameSite=None.
if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
{
return true;
}
return false;
}
}