public static void AddAuthenticationConfig(this SwaggerGenOptions c, AuthenticationType authenticationType)
        {
            switch (authenticationType)
            {
            case AuthenticationType.JwtBearer:
                var tokenPath = TokenConfiguration.GetOptions().Value.Path;
                c.DocumentFilter <TokenOperation>();
                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, c.GetTokenSecurityDefinition(tokenPath));
                c.AddSecurityRequirement(c.GetTokenSecurityRequirement());
                break;

            case AuthenticationType.Basic:
                c.AddSecurityDefinition(BasicAuthenticationDefaults.AuthenticationScheme, c.GetBasicSecurityDefinition());
                c.AddSecurityRequirement(c.GetBasicSecurityRequirement());
                break;

            case AuthenticationType.ApiKey:
                c.AddSecurityDefinition(ApiKeyAuthenticationDefaults.AuthenticationScheme, c.GetApiKeySecurityDefinition());
                c.AddSecurityRequirement(c.GetApiKeySecurityRequirement());
                break;

            case AuthenticationType.AllowAll:
                break;

            default: throw new ArgumentException(nameof(authenticationType) + " is not a valid authentication type");
            }
        }
Esempio n. 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            var folder = Configuration["staticFolder"];

            if (!string.IsNullOrEmpty(folder))
            {
                services.AddSpaStaticFiles((spa) =>
                {
                    spa.RootPath = folder;
                });

                // No need to define anything else as this can only be used as a SPA server
                return;
            }

            var jsonFilePath = Path.Combine(Configuration["currentPath"], Configuration["file"]);

            services.AddSingleton <IDataStore>(new DataStore(jsonFilePath, keyProperty: Configuration["DataStore:IdField"], reloadBeforeGetCollection: Configuration.GetValue <bool>("DataStore:EagerDataReload")));
            services.AddSingleton <IMessageBus, MessageBus>();
            services.AddSingleton <JobsService>();

            services.Configure <AuthenticationSettings>(Configuration.GetSection("Authentication"));
            services.Configure <ApiSettings>(Configuration.GetSection("Api"));
            services.Configure <DataStoreSettings>(Configuration.GetSection("DataStore"));
            services.Configure <JobsSettings>(Configuration.GetSection("Jobs"));
            services.Configure <SimulateSettings>(Configuration.GetSection("Simulate"));
            services.Configure <CustomResponseSettings>(Configuration.GetSection("CustomResponse"));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            var useAuthentication = Configuration.GetValue <bool>("Authentication:Enabled");

            _authenticationType = AuthenticationConfiguration.ReadType(Configuration);
            services.AddAuthentication(_authenticationType);

            // TODO: AddControllers
            services.AddMvc()
            .AddNewtonsoftJson()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.Configure <MvcOptions>(options =>
            {
                options.RespectBrowserAcceptHeader = true;
                options.ReturnHttpNotAcceptable    = true;

                options.OutputFormatters.Add(new CsvOutputFormatter());
                options.OutputFormatters.Add(new XmlOutputFormatter());

                // Add patches to NewtonsoftJsonPatchInputFormatter, not to NewtonsoftJsonPatchInputFormatter
                var jsonFormatter = options.InputFormatters.OfType <NewtonsoftJsonInputFormatter>().First(i => i.GetType() == typeof(NewtonsoftJsonInputFormatter));
                jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(Constants.JsonMergePatch));
                jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(Constants.MergePatchJson));
            });

            if (Configuration.GetValue <bool>("Caching:ETag:Enabled"))
            {
                services.AddResponseCaching();
                services.AddHttpCacheHeaders(
                    (expirationModelOptions) =>
                {
                    expirationModelOptions.MaxAge = 0;
                },
                    (validationModelOptions) =>
                {
                    // Use only ETag caching
                    validationModelOptions.NoCache        = true;
                    validationModelOptions.MustRevalidate = true;
                });
            }

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Fake JSON API", Version = "v1"
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "FakeServer.xml");
                c.IncludeXmlComments(xmlPath);

                if (useAuthentication)
                {
                    if (Configuration["Authentication:AuthenticationType"] == "token")
                    {
                        var tokenPath = TokenConfiguration.GetOptions().Value.Path;
                        c.DocumentFilter <TokenOperation>();
                        c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, c.GetTokenSecurityDefinition(tokenPath));
                        c.AddSecurityRequirement(c.GetTokenSecurityRequirement());
                    }
                    else
                    {
                        c.AddSecurityDefinition(BasicAuthenticationDefaults.AuthenticationScheme, c.GetBasicSecurityDefinition());
                        c.AddSecurityRequirement(c.GetBasicSecurityRequirement());
                    }
                }
            });
        }