public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); }); var dpBuilder = services.AddDataProtection(); var keyRingPath = configuration.GetValue("KEY_RING_PATH", string.Empty); if (!string.IsNullOrWhiteSpace(keyRingPath)) { dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath)); } services.AddOpenApiDocument(); services.Configure <OpenApiDocumentMiddlewareSettings>(options => { options.Path = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <SwaggerUi3Settings>(options => { options.Path = "/api/swagger"; options.DocumentPath = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; var knownNetworks = configuration.GetValue("KNOWN_NETWORKS", "::ffff:172.51.0.0/16").Split(';'); foreach (var knownNetwork in knownNetworks) { options.KnownNetworks.Add(ParseNetworkFromString(knownNetwork)); } }); services.AddDistributedMemoryCache(); services.AddSingleton <IFileSystem, FileSystem>(); services.AddTransient <ICountriesListProvider, ListsProvider>(); services.AddTransient <IStateProvincesListProvider, ListsProvider>(); services.AddTransient <IJurisdictionsListProvider, ListsProvider>(); services.AddTransient <ISupportsListProvider, ListsProvider>(); services.AddTransient <IListsGateway, DynamicsListsGateway>(); services.Configure <FileBasedCachedListsOptions>(configuration.GetSection("Dynamics:Cache")); services.AddTransient <IListsRepository, FileBasedCachedListsRepository>(); services.Configure <ADFSTokenProviderOptions>(configuration.GetSection("Dynamics:ADFS")); services.AddADFSTokenProvider(); services.AddTransient <ISubmissionRepository, SubmissionRepository>(); services.AddTransient <IReferenceNumberGenerator, ReferenceNumberGenerator>(); services.AddTransient <ISubmissionDynamicsCustomActionHandler, SubmissionDynamicsCustomActionHandler>(); services.AddScoped(sp => { var dynamicsApiEndpoint = configuration.GetValue <string>("Dynamics:DynamicsApiEndpoint"); var tokenProvider = sp.GetRequiredService <ITokenProvider>(); return(new CRMWebAPI(new CRMWebAPIConfig { APIUrl = dynamicsApiEndpoint, GetAccessToken = async(s) => await tokenProvider.AcquireToken() })); }); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); }); var dpBuilder = services.AddDataProtection(); var keyRingPath = configuration.GetValue("KEY_RING_PATH", string.Empty); if (!string.IsNullOrWhiteSpace(keyRingPath)) { dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath)); } if (!env.IsProduction()) { services.Configure <OpenApiDocumentMiddlewareSettings>(options => { options.Path = "/api/openapi/{documentName}/openapi.json"; options.DocumentName = "Registrants Portal API"; options.PostProcess = (document, req) => { document.Info.Title = "Registrants Portal API"; }; }); services.Configure <SwaggerUi3Settings>(options => { options.Path = "/api/openapi"; options.DocumentTitle = "Registrants Portal API Documentation"; options.DocumentPath = "/api/openapi/{documentName}/openapi.json"; }); services.AddOpenApiDocument(); } services.Configure <JsonOptions>(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.Configure <ADFSTokenProviderOptions>(configuration.GetSection("Dynamics:ADFS")); services.Configure <LocationCacheHostedServiceOptions>(configuration.GetSection("Location:Cache")); // TODO: consider setting a distributed cache in the future services.AddDistributedMemoryCache(); services.AddRegistrationModule(); services.AddLocationModule(); services.AddADFSTokenProvider(); services.AddSingleton(sp => { var configuration = sp.GetRequiredService <IConfiguration>(); var dynamicsApiEndpoint = configuration.GetValue <string>("Dynamics:DynamicsApiEndpoint"); var dynamicsApiBaseUri = configuration.GetValue <string>("Dynamics:DynamicsApiBaseUri"); var tokenProvider = sp.GetRequiredService <ISecurityTokenProvider>(); var logger = sp.GetRequiredService <ILogger <DynamicsClientContext> >(); return(new DynamicsClientContext(new Uri(dynamicsApiBaseUri), new Uri(dynamicsApiEndpoint), async() => await tokenProvider.AcquireToken(), logger)); }); }
public void ConfigureServices(IServiceCollection services) { //Add configuration options services.Configure <JwtTokenOptions>(opts => configuration.Bind("auth:jwt", opts)); services.Configure <JsonOptions>(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.Configure <ADFSTokenProviderOptions>(configuration.GetSection("Dynamics:ADFS")); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardLimit = 2; var configvalue = configuration.GetValue("app:knownNetwork", string.Empty)?.Split('/'); if (configvalue.Length == 2) { var knownNetwork = new IPNetwork(IPAddress.Parse(configvalue[0]), int.Parse(configvalue[1])); options.KnownNetworks.Add(knownNetwork); } }); //Add services AddDataProtection(services); AddOpenApi(services); services.AddCors(opts => opts.AddDefaultPolicy(policy => { // try to get array of origins from section array var corsOrigins = configuration.GetSection("app:cors:origins").GetChildren().Select(c => c.Value).ToArray(); // try to get array of origins from value if (!corsOrigins.Any()) { corsOrigins = configuration.GetValue("app:cors:origins", string.Empty).Split(','); } corsOrigins = corsOrigins.Where(o => !string.IsNullOrWhiteSpace(o)).ToArray(); if (corsOrigins.Any()) { policy.SetIsOriginAllowedToAllowWildcardSubdomains().WithOrigins(corsOrigins); } })); services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); }).AddNewtonsoftJson(); services.AddResponseCompression(); services.AddPortalAuthentication(configuration); services.AddAutoMapper((sp, cfg) => { cfg.ConstructServicesUsing(t => sp.GetRequiredService(t)); }, typeof(Startup)); services.AddDistributedMemoryCache(); // TODO: configure proper distributed cache services.AddSecurityModule(); services.AddADFSTokenProvider(); services.Configure <MessagingOptions>(configuration.GetSection("backend")); services.AddMessaging(); services.AddTransient <IEvacuationSearchService, EvacuationSearchService>(); }
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { configuration.GetSection("jwt").Bind(options); options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidateIssuer = true, RequireSignedTokens = true, RequireAudience = true, RequireExpirationTime = true, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(60), NameClaimType = ClaimTypes.Upn, RoleClaimType = ClaimTypes.Role, ValidateActor = true, ValidateIssuerSigningKey = true, }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = async c => { await Task.CompletedTask; var logger = c.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger("JwtBearer"); logger.LogError(c.Exception, $"Error authenticating token"); }, OnTokenValidated = async c => { await Task.CompletedTask; var logger = c.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger("JwtBearer"); logger.LogDebug("Token validated for {0}", c.ToString()); // var userService = c.HttpContext.RequestServices.GetRequiredService<IUserService>(); // c.Principal = await userService.CreatePrincipalForUser(c.Principal); // logger.LogDebug("Token validated for {0}", c.Principal.Identity.Name); } }; options.Validate(); }); services.AddAuthorization(options => { options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser(); // .RequireClaim("user_role") // .RequireClaim("user_team"); }); options.DefaultPolicy = options.GetPolicy(JwtBearerDefaults.AuthenticationScheme); }); services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); options.Filters.Add(new AuthorizeFilter()); }); var dpBuilder = services.AddDataProtection(); var keyRingPath = configuration.GetValue("KEY_RING_PATH", string.Empty); if (!string.IsNullOrWhiteSpace(keyRingPath)) { dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath)); } services.AddOpenApiDocument(); services.Configure <OpenApiDocumentMiddlewareSettings>(options => { options.Path = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <SwaggerUi3Settings>(options => { options.Path = "/api/swagger"; options.DocumentPath = "/api/swagger/{documentName}/swagger.json"; }); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; var knownNetworks = configuration.GetValue("KNOWN_NETWORKS", "::ffff:172.51.0.0/16").Split(';'); foreach (var knownNetwork in knownNetworks) { options.KnownNetworks.Add(ParseNetworkFromString(knownNetwork)); } }); services.AddDistributedMemoryCache(); services.AddSingleton <IFileSystem, FileSystem>(); services.AddTransient <ICountriesListProvider, ListsProvider>(); services.AddTransient <IStateProvincesListProvider, ListsProvider>(); services.AddTransient <IJurisdictionsListProvider, ListsProvider>(); services.AddTransient <ISupportsListProvider, ListsProvider>(); services.AddTransient <IListsGateway, DynamicsListsGateway>(); services.Configure <FileBasedCachedListsOptions>(configuration.GetSection("Dynamics:Cache")); services.AddTransient <IListsRepository, FileBasedCachedListsRepository>(); services.Configure <ADFSTokenProviderOptions>(configuration.GetSection("Dynamics:ADFS")); services.AddADFSTokenProvider(); services.AddTransient <ISubmissionRepository, SubmissionRepository>(); services.AddTransient <IReferenceNumberGenerator, ReferenceNumberGenerator>(); services.AddTransient <ISubmissionDynamicsCustomActionHandler, SubmissionDynamicsCustomActionHandler>(); services.AddScoped(sp => { var dynamicsApiEndpoint = configuration.GetValue <string>("Dynamics:DynamicsApiEndpoint"); var tokenProvider = sp.GetRequiredService <ITokenProvider>(); return(new CRMWebAPI(new CRMWebAPIConfig { APIUrl = dynamicsApiEndpoint, GetAccessToken = async(s) => await tokenProvider.AcquireToken() })); }); }