-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartup.cs
405 lines (358 loc) · 16.3 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using AppIdentity.Extensions;
using AppIdentity.Models;
using ArbitraryIdentityExtensionGrant;
using AuthRequiredDemoGraphQL.Extensions;
using Cosmonaut;
using DiscoveryHub.Extensions;
using GraphQLPlay.IdentityModelExtras;
using GraphQLPlay.IdentityModelExtras.Extensions;
using GraphQLPlayTokenExchangeOnlyApp.Filter;
using IdentityServer4.Configuration;
using IdentityServer4.Contrib.Cosmonaut.Extensions;
using IdentityServer4ExtensionGrants.Rollup.Extensions;
using IdentityServer4Extras.Extensions;
using IdentityServerRequestTracker.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using MultiAuthority.AccessTokenValidation;
using P7Core.Extensions;
using P7Core.GraphQLCore.Extensions;
using P7Core.GraphQLCore.Stores;
using P7Core.ObjectContainers.Extensions;
using P7IdentityServer4.Extensions;
using Self.Validator.Extensions;
using Swashbuckle.AspNetCore.Swagger;
using TokenExchange.Contracts;
using TokenExchange.Contracts.Extensions;
using TokenExchange.Contracts.Services;
using TokenExchange.Contracts.Stores;
using static GraphQLPlay.Rollup.Extensions.AspNetCoreExtensions;
using static TokenExchange.Rollup.Extensions.AspNetCoreExtensions;
namespace GraphQLPlayTokenExchangeOnlyApp
{
class OIDCSchemeEnabled
{
public bool Enabled { get; set; }
public string Scheme { get; set; }
}
public class Startup :
IExtensionGrantsRollupRegistrations,
IGraphQLRollupRegistrations,
ITokenExchangeRegistrations
{
private readonly IHostingEnvironment _hostingEnvironment;
public IConfiguration Configuration { get; }
private ILogger<Startup> _logger;
public Startup(IHostingEnvironment env, IConfiguration configuration, ILogger<Startup> logger)
{
_hostingEnvironment = env;
Configuration = configuration;
_logger = logger;
}
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddObjectContainer(); // use this vs a static to cache class data.
services.AddOptions();
services.Configure<ArbitraryIdentityExtensionGrantOptions>(options => { options.IdentityProvider = "Demo"; });
services.AddDistributedMemoryCache();
services.AddGraphQLPlayRollup(this);
services.AddExtensionGrantsRollup(this);
services.AddGraphQLDiscoveryTypes();
services.AddInMemoryDiscoveryHubStore();
services.AddGraphQLAuthRequiredQuery();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
corsBuilder => corsBuilder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthorization(options =>
{
options.AddPolicy("Daffy Duck",
policy => { policy.RequireClaim("client_namespace", "Daffy Duck"); });
});
// var scheme = Configuration["authValidation:scheme"];
var schemes = Configuration
.GetSection("authValidation:schemes")
.Get<List<string>>();
var section = Configuration.GetSection("InMemoryOAuth2ConfigurationStore:oauth2");
var oauth2Section = new Oauth2Section();
section.Bind(oauth2Section);
var schemeRecords = SchemeRecords(oauth2Section, schemes);
services.AddAuthentication("Bearer")
.AddMultiAuthorityAuthentication(schemeRecords);
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.TryAddTransient<IDefaultHttpClientFactory, DefaultHttpClientFactory>();
// Build the intermediate service provider then return it
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new Info { Title = "GraphQLPlayTokenExchangeOnlyApp", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
config.IncludeXmlComments(xmlPath);
config.OperationFilter<MultiAuthorityOperationFilter>();
});
services.AddInMemoryAppIdentityConfiguration(new AppIdentityConfigurationModel()
{
MaxAppIdLength = Guid.NewGuid().ToString().Length * 2,
MaxMachineIdLength = Guid.NewGuid().ToString().Length * 2,
MaxSubjectLength = Guid.NewGuid().ToString().Length * 2
});
return services.BuildServiceProvider();
}
private static List<SchemeRecord> SchemeRecords(Oauth2Section oauth2Section, List<string> schemes)
{
var authSchemes = oauth2Section.Authorities.Where(c => schemes.Any(c2 => c2 == c.Scheme));
List<SchemeRecord> schemeRecords = new List<SchemeRecord>();
foreach (var authScheme in authSchemes)
{
Func<TokenValidatedContext, Task> tokenValidationHandler = context =>
{
ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
if (identity != null)
{
// Add the access_token as a claim, as we may actually need it
var accessToken = context.SecurityToken as JwtSecurityToken;
if (accessToken != null)
{
identity.AddClaim(new Claim("access_token", accessToken.RawData));
}
}
return Task.CompletedTask;
};
var schemeRecord = new SchemeRecord()
{
Name = authScheme.Scheme,
JwtBearerOptions = options =>
{
options.Authority = authScheme.Authority;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context => Task.CompletedTask,
OnTokenValidated = tokenValidationHandler
};
}
};
schemeRecords.Add(schemeRecord);
}
return schemeRecords;
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServerRequestTrackerMiddleware();
app.UseMvc();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "GraphQLPlayTokenExchangeOnlyApp V1");
});
}
public void AddIdentityResources(IServiceCollection services, IIdentityServerBuilder builder)
{
_logger.LogInformation("AddIdentityResources to services");
var identityResources = Configuration.LoadIdentityResourcesFromSettings();
builder.AddInMemoryIdentityResources(identityResources);
}
public void AddClients(IServiceCollection services, IIdentityServerBuilder builder)
{
_logger.LogInformation("AddClients to services");
var clients = Configuration.LoadClientsFromSettings();
builder.AddInMemoryClientsExtra(clients);
}
public void AddApiResources(IServiceCollection services, IIdentityServerBuilder builder)
{
_logger.LogInformation("AddApiResources to services");
var apiResources = Configuration.LoadApiResourcesFromSettings();
builder.AddInMemoryApiResources(apiResources);
}
private readonly ConnectionPolicy _connectionPolicy = new ConnectionPolicy
{
ConnectionProtocol = Protocol.Tcp,
ConnectionMode = ConnectionMode.Direct
};
public void AddOperationalStore(IServiceCollection services, IIdentityServerBuilder builder)
{
bool useRedis = Convert.ToBoolean(Configuration["appOptions:redis:useRedis"]);
bool useCosmos = Convert.ToBoolean(Configuration["appOptions:cosmos:useCosmos"]);
if (useCosmos)
{
/*
*
"identityServerOperationalStore": {
"database": "identityServer",
"collection": "operational"
}
*/
var uri = Configuration["appOptions:cosmos:uri"];
var primaryKey = Configuration["appOptions:cosmos:primaryKey"];
var databaseName = Configuration["appOptions:cosmos:identityServerOperationalStore:database"];
var collection = Configuration["appOptions:cosmos:identityServerOperationalStore:collection"];
var cosmosStoreSettings = new CosmosStoreSettings(
databaseName,
uri,
primaryKey,
s =>
{
s.ConnectionPolicy = _connectionPolicy;
});
builder.AddOperationalStore(cosmosStoreSettings, collection);
builder.AddCosmonautIdentityServerCacheStore(cosmosStoreSettings, collection);
}
else if (useRedis)
{
var redisConnectionString = Configuration["appOptions:redis:redisConnectionString"];
builder.AddOperationalStore(options =>
{
options.RedisConnectionString = redisConnectionString;
options.Db = 1;
})
.AddRedisCaching(options =>
{
options.RedisConnectionString = redisConnectionString;
options.KeyPrefix = "prefix";
});
services.AddDistributedRedisCache(options =>
{
options.Configuration = redisConnectionString;
});
}
else
{
builder.AddInMemoryCaching();
builder.AddInMemoryPersistedGrants();
services.AddDistributedMemoryCache();
}
}
public void AddSigningServices(IServiceCollection services, IIdentityServerBuilder builder)
{
_logger.LogInformation("AddSigningServices to services");
bool useKeyVault = Convert.ToBoolean(Configuration["appOptions:keyVault:useKeyVault"]);
bool useKeyVaultSigning = Convert.ToBoolean(Configuration["appOptions:keyVault:useKeyVaultSigning"]);
_logger.LogInformation($"AddSigningServices:useKeyVault:{useKeyVault}");
_logger.LogInformation($"AddSigningServices:useKeyVaultSigning:{useKeyVaultSigning}");
if (useKeyVault)
{
builder.AddKeyVaultCredentialStore();
services.AddKeyVaultTokenCreateServiceTypes();
services.AddKeyVaultTokenCreateServiceConfiguration(Configuration);
if (useKeyVaultSigning)
{
// this signs the token using azure keyvault to do the actual signing
builder.AddKeyVaultTokenCreateService();
}
}
else
{
_logger.LogInformation("AddSigningServices AddDeveloperSigningCredential");
builder.AddDeveloperSigningCredential();
}
}
public void AddGraphQLFieldAuthority(IServiceCollection services)
{
services.TryAddSingleton<IGraphQLFieldAuthority, InMemoryGraphQLFieldAuthority>();
services.RegisterGraphQLCoreConfigurationServices(Configuration);
}
public void AddTokenValidators(IServiceCollection services)
{
services.AddInMemoryOAuth2ConfigurationStore();
services.AddSelfTokenExchangeHandler();
services.AddDemoTokenExchangeHandlers();
services.AddSelfOIDCTokenValidator();
var schemes = Configuration
.GetSection("oidcSchemes")
.Get<List<OIDCSchemeEnabled>>();
foreach (var scheme in schemes)
{
if (scheme.Enabled)
{
services.AddSingleton<ISchemeTokenValidator>(x =>
{
var oidcTokenValidator = x.GetRequiredService<OIDCTokenValidator>();
oidcTokenValidator.TokenScheme = scheme.Scheme;
return oidcTokenValidator;
});
}
}
services.AddInMemoryExternalExchangeStore();
var tempExternalExchangeStore = InMemoryExternalExchangeStore.MakeStore(Configuration);
ExternalExchangeTokenExchangeHandler.RegisterServices(services, tempExternalExchangeStore);
services.AddInMemoryPipelineExchangeStore();
var pipelineExchangeStore = InMemoryPipelineExchangeStore.MakeStore(Configuration);
PipelineTokenExchangeHandler.RegisterServices(services, pipelineExchangeStore);
}
public void AddGraphQLApis(IServiceCollection services)
{
// APIS
services.AddTokenExchangeRollup(this);
services.AddGraphQLAppIdentityTypes();
}
public Action<IdentityServerOptions> GetIdentityServerOptions()
{
Action<IdentityServerOptions> identityServerOptions = options =>
{
options.InputLengthRestrictions.RefreshToken = 256;
options.Caching.ClientStoreExpiration = TimeSpan.FromMinutes(1);
};
return identityServerOptions;
}
}
}