public async Task Invoke(HttpContext context) { // Check is request to Swagger if (!SwaggerHelper.IsAccessSwagger(context, _options)) { await _next.Invoke(context).ConfigureAwait(true); return; } // Set cookie if need string requestAccessKey = context.Request.Query[ElectSwaggerConstants.AccessKeyName]; if (!string.IsNullOrWhiteSpace(requestAccessKey) && context.Request.Cookies[ElectSwaggerConstants.AccessKeyName] != requestAccessKey) { SetCookie(context, ElectSwaggerConstants.CookieAccessKeyName, requestAccessKey); } // Check Permission bool isCanAccess = SwaggerHelper.IsCanAccessSwagger(context, _options.AccessKey); if (!isCanAccess) { context.Response.StatusCode = StatusCodes.Status403Forbidden; await context.Response.WriteAsync(_options.UnAuthorizeMessage).ConfigureAwait(true); return; } if (SwaggerHelper.IsAccessJsonViewer(context, _options)) { var jsonViewerContentResult = SwaggerHelper.GetApiJsonViewerHtml(); context.Response.ContentType = jsonViewerContentResult.ContentType; context.Response.StatusCode = jsonViewerContentResult.StatusCode ?? StatusCodes.Status200OK; await context.Response.WriteAsync(jsonViewerContentResult.Content, Encoding.UTF8).ConfigureAwait(true); return; } if (SwaggerHelper.IsAccessUI(context, _options)) { var apiDocContentResult = SwaggerHelper.GetApiDocHtml(); context.Response.ContentType = apiDocContentResult.ContentType; context.Response.StatusCode = apiDocContentResult.StatusCode ?? StatusCodes.Status200OK; await context.Response.WriteAsync(apiDocContentResult.Content, Encoding.UTF8).ConfigureAwait(true); return; } // Next middleware is swagger endpoint => generate document by swagger await _next.Invoke(context).ConfigureAwait(true); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMediatR(typeof(Startup)); services.AddMvc(); #region Repository services.AddSingleton <IGroupRepository, GroupRepository>(); services.AddSingleton <IPersonRepository, PersonRepository>(); services.AddSingleton <IMessageRepository, MessageRepository>(); #endregion #region AutoMapper MapperConfiguration mapperConfig = new MapperConfiguration(a => { a.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); #endregion #region Swagger services.AddSwaggerGen(a => { a.SwaggerDoc(SwaggerHelper.Version, SwaggerHelper.GetOpenApiInfo()); //a.IncludeXmlComments(SwaggerHelper.GetXmlComments()); }); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // Identity services.AddDbContext <SecurityContext>(options => options.UseNpgsql(Configuration.GetConnectionString("Default"), x => x.MigrationsHistoryTable("__MigrationsHistory", SecurityContext.DEFAULT_SCHEMA))); IdentityHelper.ConfigureService(services); // Helpers AuthenticationHelper.ConfigureService(services, Configuration["JwtSecurityToken:Issuer"], Configuration["JwtSecurityToken:Audience"], Configuration["JwtSecurityToken:Key"]); CorsHelper.ConfigureService(services); SwaggerHelper.ConfigureService(services); // Settings services.Configure <EmailSettings>(Configuration.GetSection("Email")); services.Configure <ClientAppSettings>(Configuration.GetSection("ClientApp")); services.Configure <JwtSecurityTokenSettings>(Configuration.GetSection("JwtSecurityToken")); services.Configure <QRCodeSettings>(Configuration.GetSection("QRCode")); // Services services.AddTransient <IEmailService, EmailService>(); // Azure // Azure Storage Services services.AddScoped <IBlobStorage>(s => new BlobStorage(Configuration["ConnectionStrings:AzureStorage"], Configuration["AzureStorage:ContainerName"], Configuration["AzureStorage:Url"])); services.AddScoped <IQueueStorage>(s => new QueueStorage(Configuration["ConnectionStrings:AzureStorage"])); // Data }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (!env.IsProduction()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); HealthCheckHelper.Setup(app); BeatPulseHelper.Setup(app); SwaggerHelper.Setup(app); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (!env.IsProduction()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseCors(policy => policy.WithOrigins("https://localhost:44328").AllowAnyMethod().AllowAnyHeader().AllowCredentials()); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSignalR(routes => { routes.MapHub <NotificationHub>("/notification"); }); HealthCheckHelper.Setup(app); BeatPulseHelper.Setup(app); SwaggerHelper.Setup(app); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public static IServiceCollection AddElectSwagger(this IServiceCollection services, [NotNull] Action <ElectSwaggerOptions> configuration) { services.Configure(configuration); var options = configuration.GetValue(); if (!options.IsEnable) { return(services); } // Update File Content base on Configuration SwaggerHelper.UpdateApiDocFileContent(options.Title, SwaggerHelper.GetSwaggerEndpoint(options), options.AuthTokenType, options.JsonViewerUrl); SwaggerHelper.UpdateApiJsonViewerFileContent(options.Title); // Config Swagger services.AddSwaggerGen(swaggerGenOptions => { swaggerGenOptions.AddElectSwaggerGenOptions(configuration); options.ExtendOptions?.Invoke(swaggerGenOptions, options); }); return(services); }
static SchemaSwaggerGenerator() { SchemaBodyDescription = SwaggerHelper.LoadDocs("schemabody"); SchemaQueryDescription = SwaggerHelper.LoadDocs("schemaquery"); ReaderSecurity = new List <SwaggerSecurityRequirement> { new SwaggerSecurityRequirement { { Constants.SecurityDefinition, new[] { SquidexRoles.AppReader } } } }; EditorSecurity = new List <SwaggerSecurityRequirement> { new SwaggerSecurityRequirement { { Constants.SecurityDefinition, new[] { SquidexRoles.AppEditor } } } }; }
private static SwaggerOwinSettings ConfigureIdentity(this SwaggerOwinSettings settings, MyUrlsOptions urlOptions) { settings.DocumentProcessors.Add( new SecurityDefinitionAppender(Constants.SecurityDefinition, SwaggerHelper.CreateOAuthSchema(urlOptions))); settings.OperationProcessors.Add(new OperationSecurityScopeProcessor(Constants.SecurityDefinition)); return(settings); }
public static SwaggerSettings <T> ConfigureIdentity <T>(this SwaggerSettings <T> settings, MyUrlsOptions urlOptions) where T : SwaggerGeneratorSettings, new() { settings.GeneratorSettings.DocumentProcessors.Add( new SecurityDefinitionAppender( Constants.SecurityDefinition, SwaggerHelper.CreateOAuthSchema(urlOptions))); settings.GeneratorSettings.OperationProcessors.Add(new ScopesProcessor()); return(settings); }
private void ConfigureHelpers(IServiceCollection services) { HelpersManager.Configure(_correlationId, services, Configuration); CommonPatterns.Filters.ExceptionFilter.Configure(services); CommonPatterns.Filters.RequestResponseFilter.Configure(services); SwaggerHelper.Configure(services); CacheHelper.Configure(services); HealthCheckHelper.Configure(services); BeatPulseHelper.Configure(services, Configuration); WhoIsHelper.Configure(services); }
private void HelperInjections(IServiceCollection services) { HelpersManager.Configure(_correlationId, services, Configuration); ExceptionFilter.Configure(services); RequestResponseFilter.Configure(services); RefreshRobotCacheFilter.Configure(services); RefreshCyborgCacheFilter.Configure(services); SwaggerHelper.Configure(services); CacheHelper.Configure(services); HealthCheckHelper.Configure(services); BeatPulseHelper.Configure(services, Configuration); WhoIsHelper.Configure(services); }
public async Task<SwaggerDocument> Generate(IAppEntity app, IEnumerable<ISchemaEntity> schemas) { document = SwaggerHelper.CreateApiDocument(context, urlOptions, app.Name); schemaGenerator = new SwaggerJsonSchemaGenerator(settings); schemaResolver = new SwaggerSchemaResolver(document, settings); GenerateSchemasOperations(schemas, app); await GenerateDefaultErrorsAsync(); return document; }
public SchemasSwaggerGenerator(IHttpContextAccessor context, SwaggerOwinSettings swaggerSettings, IOptions <MyUrlsOptions> urlOptions) { this.context = context.HttpContext; this.urlOptions = urlOptions.Value; schemaGenerator = new SwaggerJsonSchemaGenerator(swaggerSettings); schemaResolver = new SwaggerSchemaResolver(document, swaggerSettings); swaggerGenerator = new SwaggerGenerator(schemaGenerator, swaggerSettings, schemaResolver); schemaBodyDescription = SwaggerHelper.LoadDocs("schemabody"); schemaQueryDescription = SwaggerHelper.LoadDocs("schemaquery"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); HttpClientHelper.ConfigureService(services, Configuration); DataDependencyLoader.ConfigureService(services); DomainDependencyLoader.ConfigureService(services); SwaggerHelper.ConfigureService(services); /*services.AddCors(options => * { * options.AddPolicy("default", builder => * { * builder. * }); * })*/ }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("default", policy => { policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddAutoMapper(); DatabaseHelper.SetConnection(services, Configuration); DependencyInjectionHelper.Register(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); SwaggerHelper.SetService(services); }
public static IApplicationBuilder UseElectSwagger(this IApplicationBuilder app) { var options = app.ApplicationServices.GetService <IOptions <ElectSwaggerOptions> >().Value; app.UseSwagger(c => { c.RouteTemplate = options.SwaggerRoutePrefix + "/{documentName}/" + options.SwaggerName; c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value); }); app.UseSwaggerUI(c => { // RoutePrefix of Swagger UI must not start by / or ~ c.RoutePrefix = options.SwaggerRoutePrefix; c.SwaggerEndpoint(SwaggerHelper.GetSwaggerEndpoint(options), options.AccessKey); }); // Path and GZip for Statics Content app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Bootstrapper.Instance.WorkingFolder), RequestPath = ElectSwaggerConstants.AssetsUrl, OnPrepareResponse = context => { var headers = context.Context.Response.GetTypedHeaders(); headers.CacheControl = new CacheControlHeaderValue { MaxAge = new TimeSpan(365, 0, 0, 0) }; } }); app.UseMiddleware <ElectSwaggerMiddleware>(); return(app); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext <CitasContext>(options => options.UseNpgsql(Configuration.GetConnectionString("Default"), x => x.MigrationsHistoryTable("__MigrationsHistory", CitasContext.DEFAULT_SCHEMA))); SwaggerHelper.ConfigureService(services); services .AddCustomMvc() .AddCustomIntegrations(Configuration) .AddCustomConfiguration(Configuration); services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //https://github.com/shammelburg/CoreIdentity // Identity services.AddDbContext <Api.Identity.SecurityContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"])); // Tools->NuGet Package Manager -> Package Manager Console // Initialise // add-migration init -Context SecurityContext // update or create DB // update-database -Context SecurityContext IdentityHelper.ConfigureService(services); // Helpers AuthenticationHelper.ConfigureService(services, Configuration["JwtSecurityToken:Issuer"], Configuration["JwtSecurityToken:Audience"], Configuration["JwtSecurityToken:Key"]); CorsHelper.ConfigureService(services); SwaggerHelper.ConfigureService(services); // Settings services.Configure <EmailSettings>(Configuration.GetSection("Email")); services.Configure <ClientAppSettings>(Configuration.GetSection("ClientApp")); services.Configure <JwtSecurityTokenSettings>(Configuration.GetSection("JwtSecurityToken")); //services.Configure<QRCodeSettings>(Configuration.GetSection("QRCode")); // Services services.AddTransient <IEmailService, EmailService>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddTransient <IUnitOfWork, UnitOfWork>(); services.AddControllers(); services.AddHttpContextAccessor(); // Mapper services.AddAutoMapper(typeof(AutoMapping)); //Define upload services.Configure <FormOptions>(o => { o.ValueLengthLimit = int.MaxValue; o.MultipartBodyLengthLimit = int.MaxValue; o.MemoryBufferThreshold = int.MaxValue; }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework. app.UseCors(DefaultCorsPolicyName); // Enable CORS! app.UseStaticFiles(); app.UseAuthentication(); app.UseAbpRequestLocalization(); #if FEATURE_SIGNALR // Integrate with OWIN app.UseAppBuilder(ConfigureOwinServices); #elif FEATURE_SIGNALR_ASPNETCORE app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); }); #endif app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(SwaggerHelper.ConfigureSwaggerUI(_appConfiguration["App:ServerRootAddress"])); }
/// <summary> /// Setup swagger for application /// </summary> /// <param name="services">The service where we register swagger</param> /// <param name="apiConfiguration">The swagger configuration</param> public static void AddMaijeDocumentation(this IServiceCollection services) { var configuration = services.BuildServiceProvider().GetRequiredService <IOptions <MaijeConfiguration> >().Value; services.AddSwaggerGen(options => { if (configuration.OAuth2Enabled) { ConfigureAuthentication(options, configuration.Authentication); } // resolve the IApiVersionDescriptionProvider service // note: that we have to build a temporary service provider here because one has not been created yet var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>(); // add a swagger document for each discovered API version // note: you might choose to skip or document deprecated API versions differently foreach (var description in provider.ApiVersionDescriptions) { options.DescribeAllParametersInCamelCase(); options.SwaggerDoc(description.GroupName, SwaggerHelper.CreateInfoForApiVersion(description, configuration)); } options.CustomSchemaIds(SwaggerHelper.GetCustomSchemaId); // Configure AllOf property of the swagger.json options.SchemaFilter <SubtypeOfAttributeFilter>(); // add a custom operation filter which sets default values options.OperationFilter <DefaultOperationsFilter>(); // workaround with ApiExplorer who don't lower case controller name options.DocumentFilter <LowercaseDocumentFilter>(); // integrate xml comments options.IncludeXmlComments(SwaggerHelper.GetXmlCommentsFilePath()); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Identity services.AddDbContext <SecurityContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:Default"])); // Tools->NuGet Package Manager -> Package Manager Console // Initialise // add-migration init -Context SecurityContext // update or create DB // update-database -Context SecurityContext IdentityHelper.ConfigureService(services); // Helpers AuthenticationHelper.ConfigureService(services, Configuration["JwtSecurityToken:Issuer"], Configuration["JwtSecurityToken:Audience"], Configuration["JwtSecurityToken:Key"]); CorsHelper.ConfigureService(services); SwaggerHelper.ConfigureService(services); // Settings services.Configure <EmailSettings>(Configuration.GetSection("Email")); services.Configure <ClientAppSettings>(Configuration.GetSection("ClientApp")); services.Configure <JwtSecurityTokenSettings>(Configuration.GetSection("JwtSecurityToken")); services.Configure <QRCodeSettings>(Configuration.GetSection("QRCode")); // Services services.AddTransient <IEmailService, EmailService>(); // Azure // Azure Storage Services services.AddScoped <IBlobStorage>(s => new BlobStorage(Configuration["ConnectionStrings:AzureStorage"], Configuration["AzureStorage:ContainerName"], Configuration["AzureStorage:Url"])); services.AddScoped <IQueueStorage>(s => new QueueStorage(Configuration["ConnectionStrings:AzureStorage"])); // Data services.AddDbContextPool <DataContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:Default"])); services.AddScoped <IExampleRepo, ExampleRepo>(); services.AddControllers(); }
public static IApplicationBuilder UseElectSwagger(this IApplicationBuilder app) { var options = app.ApplicationServices.GetService <IOptions <ElectSwaggerOptions> >().Value; if (!options.IsEnable) { return(app); } app.UseSwagger(c => { c.RouteTemplate = options.SwaggerRoutePrefix + "/{documentName}/" + options.SwaggerName; c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { var host = httpReq.Host.Host; if (httpReq.Headers.TryGetValue("X-Forwarded-Host", out var forwardedHost)) { host = forwardedHost; } var port = httpReq.Host.Port; if (httpReq.Headers.TryGetValue("X-Forwarded-Port", out var forwardedPort)) { if (int.TryParse(forwardedPort, out var forwardedPortInt)) { port = forwardedPortInt; } } swaggerDoc.Host = host + (port.HasValue ? $":{port.Value}" : string.Empty); }); }); app.UseSwaggerUI(c => { // RoutePrefix of Swagger UI must not start by / or ~ c.RoutePrefix = options.SwaggerRoutePrefix; c.SwaggerEndpoint(SwaggerHelper.GetSwaggerEndpoint(options), options.AccessKey); }); // Path and GZip for Statics Content app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Bootstrapper.Instance.WorkingFolder), RequestPath = ElectSwaggerConstants.AssetsUrl, OnPrepareResponse = context => { var headers = context.Context.Response.GetTypedHeaders(); headers.CacheControl = new CacheControlHeaderValue { MaxAge = new TimeSpan(365, 0, 0, 0) }; } }); app.UseMiddleware <ElectSwaggerMiddleware>(); return(app); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <IISServerOptions>(options => { options.AllowSynchronousIO = true; }); services.AddElmah <XmlFileErrorLog>(options => { options.Path = @"elmah"; options.LogPath = Path.Combine(_hostEnvironment.ContentRootPath, "App_Data", "ElmahLogs"); //options.CheckPermissionAction = context => context.User.Identity.IsAuthenticated; //note: looks like we have to use cookies for it }); services.AddMvcCore(options => { options.SuppressInputFormatterBuffering = true; options.EnableEndpointRouting = false; options.Conventions.Add(new ApiExplorerGroupPerVersionConvention()); options.EnableDynamicDtoBinding(); options.AddDynamicAppServices(services); }) .AddApiExplorer() .AddNewtonsoftJson(options => { options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset; }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); IdentityRegistrar.Register(services); AuthConfigurer.Configure(services, _appConfiguration); services.AddSignalR(); services.AddCors(); // Swagger - Enable this line and the related lines in Configure method to enable swagger UI services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); options.IgnoreObsoleteActions(); options.AddXmlDocuments(); options.OperationFilter <SwaggerOperationFilter>(); options.CustomSchemaIds(type => SwaggerHelper.GetSchemaId(type)); options.CustomOperationIds(desc => desc.ActionDescriptor is ControllerActionDescriptor d ? d.ControllerName.ToCamelCase() + d.ActionName.ToPascalCase() : null); options.SwaggerDoc("v1", new OpenApiInfo() { Title = "Shesha API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.AddDocumentsPerService(); // Define the BearerAuth scheme that's in use options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); options.SchemaFilter <DynamicDtoSchemaFilter>(); }); //services.AddApiVersioning(options => //{ // options.AssumeDefaultVersionWhenUnspecified = true; // options.DefaultApiVersion = ApiVersion.Default; // options.ReportApiVersions = true; //}); //services.AddVersionedApiExplorer(options => //{ // options.GroupNameFormat = "'v'VVV"; // options.SubstituteApiVersionInUrl = true; //}); services.AddHttpContextAccessor(); services.AddHangfire(config => { config.UseSqlServerStorage(_appConfiguration.GetConnectionString("Default")); }); // ToDo: fix AbpAuthorizationFilter services.AddMvc(options => { options.Filters.AddService(typeof(SheshaAuthorizationFilter)); }); // Add ABP and initialize // Configure Abp and Dependency Injection return(services.AddAbp <SheshaWebHostModule>( options => { // Configure Log4Net logging options.IocManager.IocContainer.AddFacility <LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config")); // configure plugins //options.PlugInSources.AddFolder(Path.Combine(_hostingEnvironment.WebRootPath, "Plugins"), SearchOption.AllDirectories); } )); }
public void ConfigureServices(IServiceCollection services) { services.AddSingleton(redisConfiguration); services.AddSingleton(urlBuilderConfiguration); services.AddSingleton(databaseConfiguration); // ** Authentication ** // services.AddAuthentication("Bearer") .AddJwtBearer(options => { options.Authority = urlBuilderConfiguration.Auth.Url; options.Audience = "wpc-netflix-apis"; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" }; if (this.environment.IsDevelopment()) { options.RequireHttpsMetadata = false; } }); services.AddMongoDb(); services .AddDataProtection() .SetApplicationName("wpc-netflix") .PersistKeysToRedis(redisConfiguration.Connection, "my-dataProtection-keys"); services.AddDistributedRedisCache(options => { options.Configuration = this.redisConfiguration.ConfigurationOptions.ToString(); }); // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" services .AddMvcCore() .AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddMvc(); services.AddApiVersioning(o => o.ReportApiVersions = true); if (!this.environment.IsProduction()) { services.AddSwaggerGen( options => { // resolve the IApiVersionDescriptionProvider service // note: that we have to build a temporary service provider here because one has not been created yet var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>(); // add a swagger document for each discovered API version // note: you might choose to skip or document deprecated API versions differently foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, SwaggerHelper.CreateInfoForApiVersion(description)); } // add a custom operation filter which sets default values options.OperationFilter <SwaggerDefaultValues>(); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; // integrate xml comments // options.IncludeXmlComments(SwaggerHelper.XmlCommentsFilePath); // Authorization API documentation options.OperationFilter <AuthResponsesOperationFilter>(); options.OperationFilter <BadRequestResponseOperationFilter>(); options.OperationFilter <TagByApiExplorerSettingsOperationFilter>(); // Authentication var oAuth2Scheme = new OAuth2Scheme(); oAuth2Scheme.AuthorizationUrl = urlBuilderConfiguration.Auth.Url + "/connect/authorize"; oAuth2Scheme.Flow = "implicit"; oAuth2Scheme.TokenUrl = urlBuilderConfiguration.Auth.Url + "/connect/authorize"; oAuth2Scheme.Scopes = new ConcurrentDictionary <string, string>(); oAuth2Scheme.Scopes.Add(new KeyValuePair <string, string>("admin", "Admin APIs access.")); oAuth2Scheme.Scopes.Add(new KeyValuePair <string, string>("www", "Www APIs access.")); options.AddSecurityDefinition("Bearer", oAuth2Scheme); }); } }
private void GenerateSecurityDefinitions() { document.SecurityDefinitions.Add("OAuth2", SwaggerHelper.CreateOAuthSchema(urlOptions)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Loading AutoMapper Profile var config = new AutoMapper.MapperConfiguration(cfg => { cfg.AddProfile(new GarbProfile()); }); var mapper = config.CreateMapper(); // Adding CORS services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); })); // Adding authentication services services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); // Add framework services. services.AddDbContext <GarbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("GarbDatabase"))); //.AddUnitOfWork<GarbContext>(); services.AddAutoMapper(); services.AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddMvc(); services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddApiVersioning(o => { o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); }); services.AddSwaggerGen(options => { var provider = services.BuildServiceProvider() .GetRequiredService <IApiVersionDescriptionProvider>(); foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, SwaggerHelper.CreateInfoForApiVersion(description)); } // add a custom operation filter which sets default values options.OperationFilter <SwaggerDefaultValues>(); // integrate xml comments options.IncludeXmlComments(SwaggerHelper.XmlCommentsFilePath); }); // Added - uses IOptions<T> for your settings. services.AddOptions(); // Added - Confirms that we have a home for our DemoSettings services.Configure <StorageHelper>(Configuration.GetSection("StorageHelperSettings")); services.Configure <LdapHelper>(Configuration.GetSection("Authentication")); //call this in case you need aspnet-user-authtype/aspnet-user-identity //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
static SchemaSwaggerGenerator() { schemaBodyDescription = SwaggerHelper.LoadDocs("schemabody"); schemaQueryDescription = SwaggerHelper.LoadDocs("schemaquery"); }