示例#1
0
        public static IServiceCollection AddSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "TriviaTen API", Version = "v1"
                });

                var apiKeyScheme = new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Enter authorization key in the format: 'Bearer {ACCESS TOKEN}'",
                    Name        = "Authorization",
                    Type        = "apiKey"
                };

                options.AddSecurityDefinition("Bearer", apiKeyScheme);

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() }
                });
            });

            return(services);
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IAccountRepository, AccountRepository>();
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("RestfulStandard01", new Info {
                    Title = "API接口", Version = "v1", Contact = new Contact {
                        Email = "", Name = "NetStars", Url = ""
                    }, Description = "医API"
                });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, $"RestfulStandard01.xml");
                options.IncludeXmlComments(xmlPath);

                var api = new ApiKeyScheme {
                    In = "header", Description = "请输入带有Bearer的Token", Name = "Authorization", Type = "apiKey"
                };
                options.AddSecurityDefinition("Bearer", api);
                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });
            services.AddMvc(options =>
            {
                options.ReturnHttpNotAcceptable = true;
                //通过此设置来确定是否启用ViewModel验证
                options.MaxModelValidationErrors = 200;

                options.AllowValidatingTopLevelNodes = false;
            })
            .AddXmlSerializerFormatters()                                                                 //设置支持XML格式输入输出
            .AddJsonOptions(op => op.SerializerSettings.ContractResolver = new DefaultContractResolver()) //大小写不转换
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        public static IServiceCollection AddSwagger(
            this IServiceCollection services,
            string title,
            string version,
            string defaultScheme = "Bearer")
        {
            var info = new Info
            {
                Title   = title,
                Version = version
            };
            var securityScheme = new ApiKeyScheme
            {
                Type        = "apiKey",
                In          = "Header",
                Name        = "Authorization",
                Description = $"Input \"{defaultScheme} {{token}}\" (without quotes)"
            };

            services.AddSwaggerGen(setup =>
            {
                setup.SwaggerDoc(version, info);
                setup.AddSecurityDefinition(defaultScheme, securityScheme);
                setup.OperationFilter <SecurityRequirementsOperationFilter>();
            });
            return(services);
        }
示例#4
0
        /// <summary>
        /// Adds Swagger to the services.
        /// </summary>
        /// <param name="value">The <see cref="IServiceCollection"/> to add the service to.</param>
        /// <param name="environment">The current hosting environment.</param>
        /// <returns>
        /// The value specified by <paramref name="value"/>.
        /// </returns>
        public static IServiceCollection AddSwagger(this IServiceCollection value, IHostingEnvironment environment)
        {
            return(value.AddSwaggerGen(
                       (p) =>
            {
                var provider = value.BuildServiceProvider();
                var options = provider.GetRequiredService <SiteOptions>();

                var terms = new UriBuilder()
                {
                    Scheme = "https",
                    Host = options.Metadata.Domain,
                    Path = "terms-of-service/",
                };

                var info = new Info()
                {
                    Contact = new Contact()
                    {
                        Name = options.Metadata.Author.Name,
                        Url = options.Metadata.Repository,
                    },
                    Description = options.Metadata.Description,
                    License = new License()
                    {
                        Name = "Apache 2.0",
                        Url = "http://www.apache.org/licenses/LICENSE-2.0.html",
                    },
                    TermsOfService = terms.Uri.ToString(),
                    Title = options.Metadata.Name,
                    Version = string.Empty,
                };

                p.DescribeAllEnumsAsStrings();
                p.DescribeStringEnumsInCamelCase();

                p.IgnoreObsoleteActions();
                p.IgnoreObsoleteProperties();

                AddXmlCommentsIfExists(p, environment, "LondonTravel.Site.xml");

                p.SwaggerDoc("api", info);

                p.SchemaFilter <ExampleFilter>();

                p.OperationFilter <ExampleFilter>();
                p.OperationFilter <RemoveStyleCopPrefixesFilter>();
                p.OperationFilter <SecurityRequirementsOperationFilter>();

                var securityScheme = new ApiKeyScheme()
                {
                    In = "header",
                    Name = "Authorization",
                    Type = "apiKey",
                    Description = "Access token authentication using a bearer token."
                };

                p.AddSecurityDefinition(SecurityRequirementsOperationFilter.SchemeName, securityScheme);
            }));
        }
示例#5
0
文件: Startup.cs 项目: qccoders/QCVOC
        private static void ConfigureSwaggerGenOptions(SwaggerGenOptions options, IServiceCollection services)
        {
            var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
            }

            options.DocInclusionPredicate((docName, apiDesc) =>
            {
                var versions = apiDesc.ControllerAttributes()
                               .OfType <ApiVersionAttribute>()
                               .SelectMany(attr => attr.Versions);

                return(versions.Any(v => $"v{v.ToString()}" == docName));
            });

            options.IncludeXmlComments(GetXmlCommentsFilePath());

            var apiKeyScheme = new ApiKeyScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name        = "Authorization",
                In          = "header",
                Type        = "apiKey",
            };

            options.AddSecurityDefinition("Bearer", apiKeyScheme);

            options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
            {
                { "Bearer", new string[] { } }
            });
        }
示例#6
0
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JObject        jsonObject = JObject.Load(reader);
            SecurityScheme scheme     = null;
            string         type       = jsonObject["type"].ToString();

            switch (type)
            {
            case "apiKey":
                scheme = new ApiKeyScheme();
                break;

            case "oauth2":
                scheme = new OAuth2Scheme();
                break;

            case "basic":
                scheme = new BasicAuthScheme();
                break;

            default:
                throw new ArgumentException($"Unexpected security scheme '{type}'");
            }

            serializer.Populate(jsonObject.CreateReader(), scheme);
            return(scheme);
        }
        internal static IServiceCollection AddSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(setup =>
            {
                var documentationPath = Path.Combine(AppContext.BaseDirectory, "YngStrs.PersonalityTests.Api.Documentation.xml");

                if (!File.Exists(documentationPath))
                {
                    return;
                }

                setup.IncludeXmlComments(documentationPath);

                var securityScheme = new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Enter 'Bearer {token}' (don't forget to add 'bearer') into the field below.",
                    Name        = "Authorization",
                    Type        = "apiKey"
                };

                setup.AddSecurityDefinition("Bearer", securityScheme);

                setup.SwaggerDoc("v1", new Info {
                    Title = "PersonalityTests.Api", Version = "v1"
                });

                setup.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            return(services);
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(options =>
            {
                string basePath   = AppContext.BaseDirectory;
                string moduleName = GetType().GetTypeInfo().Module.Name.Replace(".dll", ".xml");
                string filePath   = Path.Combine(basePath, moduleName);

                ApiKeyScheme scheme = Configuration.GetSection("ApiKeyScheme").Get <ApiKeyScheme>();
                options.AddSecurityDefinition("Authentication", scheme);

                Info info = Configuration.GetSection("Info").Get <Info>();

                options.IncludeXmlComments(filePath);
                options.DescribeAllEnumsAsStrings();

                options.SwaggerDoc("v1",
                                   new Info
                {
                    Title          = "Api - Autenticação",
                    Version        = "v1",
                    Description    = "Api desenvolvida na Pós graduação em arquitetura de software. A WebApi em .Net Core consiste em rotas básicas que simulam o funcionamento de uma api de autenticação.",
                    TermsOfService = "None",
                    Contact        = new Contact
                    {
                        Name = "Daniel Pimentel",
                        Url  = "https://github.com/danielkansaon/Api-Autenticacao"
                    }
                });
                // options.OperationFilter<ExamplesOperationFilter>();
            });
        }
示例#9
0
 private void SetDefaultApiKeyScheme()
 {
     this.ApiKeyScheme = new ApiKeyScheme {
         In          = "header",
         Description = "Please enter JWT with Bearer into field",
         Name        = "Authorization",
         Type        = "apiKey"
     };
 }
示例#10
0
        public static void AddSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(setup =>
            {
                var documentationPath = Path.Combine(AppContext.BaseDirectory, "Cafe.Api.Documentation.xml");

                if (File.Exists(documentationPath))
                {
                    setup.IncludeXmlComments(documentationPath);

                    var securityScheme = new ApiKeyScheme
                    {
                        In          = "header",
                        Description = "Enter 'Bearer {token}' (don't forget to add 'bearer') into the field below.",
                        Name        = "Authorization",
                        Type        = "apiKey"
                    };

                    setup.AddSecurityDefinition(
                        "Bearer",
                        securityScheme);

                    var info = new Info
                    {
                        Contact = new Contact
                        {
                            Email = "*****@*****.**",
                            Name  = "Dobromir Nikolov",
                            Url   = "https://devadventures.net"
                        },
                        License = new License
                        {
                            Name = "License",
                            Url  = "https://opensource.org/licenses/MIT"
                        },
                        Title   = "Café",
                        Version = "v1",

                        // Indentation is important for markdown to work
                        Description = @"An example domain-driven application.

Features **CQRS**, **event-sourcing**, **REST** with **HATEOAS**, **CI**/**CD** and a complete integration tests suite.

Find out more on [GitHub](https://github.com/dnikolovv/cafe).

---"
                    };

                    setup.SwaggerDoc("v1", info);

                    setup.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                    {
                        { "Bearer", Enumerable.Empty <string>() },
                    });
                }
            });
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var secret_key_api = Configuration.GetValue <string>("Secret-Key-Api");

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidatorBehavior <,>));
            services.AddSingleton <IUnitOfWork, UnitOfWorkFake>();
            services.AddSingleton <IContaCorrenteRepository, ContaCorrenteRepositoryInMemory>();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = ApiKeyDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = ApiKeyDefaults.AuthenticationScheme;
            }).AddApiKey(options =>
            {
                options.Header    = "X-API-KEY";
                options.HeaderKey = string.Empty;
                options.Events    = new ApiKeyEvents
                {
                    OnApiKeyValidated = context =>
                    {
                        if (context.ApiKey == secret_key_api)
                        {
                            context.Principal = new ClaimsPrincipal();
                            context.Success();
                        }

                        return(Task.CompletedTask);
                    }
                };
            });
            services.AddMvc()
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMediatR(typeof(Startup));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title   = "AccountManager API",
                    Version = "v1"
                });

                var s = new ApiKeyScheme
                {
                    Description = "Simples Header X-API-KEY",
                    In          = "header",
                    Name        = "X-API-KEY",
                    Type        = "apiKey"
                };

                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "ApiKeyAuth", new string[] { } }
                });
                c.AddSecurityDefinition("ApiKeyAuth", s);
            });
        }
示例#12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // requires
            // using RazorPagesMovie.Models;
            // using Microsoft.EntityFrameworkCore;
            var connection = Configuration["ConexaoMySql:MySqlConnectionString"];

            services.AddDbContext <LivrariaContext>(options =>
                                                    options.UseMySql(connection)
                                                    );

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Configurando o serviço de documentação do Swagger
            services.AddSwaggerGen(options =>
            {
                string basePath   = AppContext.BaseDirectory;
                string moduleName = GetType().GetTypeInfo().Module.Name.Replace(".dll", ".xml");
                string filePath   = Path.Combine(basePath, moduleName);
                //string readme = File.ReadAllText(Path.Combine(basePath, "README.md"));

                ApiKeyScheme scheme = Configuration.GetSection("ApiKeyScheme").Get <ApiKeyScheme>();
                options.AddSecurityDefinition("Authentication", scheme);

                Info info = Configuration.GetSection("Info").Get <Info>();
                // info.Description = readme;
                // options.SwaggerDoc(info.Version, info);

                options.IncludeXmlComments(filePath);
                options.DescribeAllEnumsAsStrings();

                options.SwaggerDoc("v1",
                                   new Info
                {
                    Title          = "Trabalho de Arquitetura Backend - Aula 02",
                    Version        = "v1",
                    Description    = "Implementação de WebApi com documentação em DotNet Core",
                    TermsOfService = "None",
                    Contact        = new Contact
                    {
                        Name = "Flávio Pedrosa",
                        Url  = "https://github.com/flaviopedrosa"
                    },
                    License = new License
                    {
                        Name = "GPL",
                        Url  = "https://example.com/license"
                    }
                });
                // options.OperationFilter<ExamplesOperationFilter>();
            });
        }
示例#13
0
 public SwaggerStartupConfigureServices(IServiceCollection serviceCollection, string tokenType = "Bearer", ApiKeyScheme apiKeyScheme = null)
 {
     this.ServiceCollection = serviceCollection;
     if (apiKeyScheme == null)
     {
         this.SetDefaultApiKeyScheme();
     }
     else
     {
         this.ApiKeyScheme = apiKeyScheme;
     }
     this.TokenType = tokenType;
     this.ConfigureServices();
 }
 public SwaggerStartupConfigureServices(IServiceCollection serviceCollection, string tokenType = "Bearer", ApiKeyScheme apiKeyScheme = null)
 {
     this.ServiceCollection = serviceCollection;
     if (apiKeyScheme == null && tokenType != null && tokenType.Equals("Bearer", StringComparison.OrdinalIgnoreCase))
     {
         this.SetDefaultApiKeyScheme();
     }
     else
     {
         this.ApiKeyScheme = apiKeyScheme;
     }
     this.TokenType = tokenType;
     this.ConfigureServices();
 }
示例#15
0
        /// <summary>
        /// Extension method to to Swagger
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureSwagger(this IServiceCollection services)
        {
            var assemblyName   = string.Concat(Assembly.GetExecutingAssembly().GetName().Name, ".xml");
            var pathToAssembly = Path.Combine(AppContext.BaseDirectory, assemblyName);

            services.AddSwaggerGen(ops =>
            {
                ops.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info()
                {
                    Title       = "Simple API service for testing Angular",
                    Version     = "v1",
                    Description = $"API Service based on JWT authentication" +
                                  $"{Environment.NewLine}" +
                                  $"Where registered user can GET, ADD or DELETE products" +
                                  $"{Environment.NewLine}" +
                                  $"{Environment.NewLine}" +
                                  $"There is two roles: <b> User, Admin </b>" +
                                  $"{Environment.NewLine}" +
                                  $"{Environment.NewLine}" +
                                  $"<b>User</b>  => Can GET and ADD products, also may DELETE products that has been created by this User" +
                                  $"{Environment.NewLine}" +
                                  $"<b>Admin</b> => Can do the same, BUT may also delete all products no matter which user added it"
                });

                ops.IncludeXmlComments(pathToAssembly);

                #region Swagger Authorization Configuration

                var securitySchema = new ApiKeyScheme()
                {
                    Description = "Please insert JWT with Bearer into field",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                };

                ops.AddSecurityDefinition("Bearer", securitySchema);

                var securityDictionary = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Array.Empty <string>() }
                };
                ops.AddSecurityRequirement(securityDictionary);

                #endregion
            });
        }
示例#16
0
        public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration, string name, string version)
        {
            return(services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(version, new Info {
                    Title = name, Version = version
                });
                c.SchemaFilter <SwaggerDBSchemaFilter>();
                c.OperationFilter <SwaggerFileUploadOperationFilter>();
                c.ParameterFilter <SwaggerEnumParameterFilter>();

                c.MapType <Stream>(() => new Schema {
                    Type = "file"
                });
                c.MapType <MemoryStream>(() => new Schema {
                    Type = "file"
                });
                c.MapType <FileStream>(() => new Schema {
                    Type = "file"
                });
                c.MapType <FileStreamResult>(() => new Schema {
                    Type = "file"
                });

                c.UseReferencedDefinitionsForEnums();
                c.DescribeAllEnumsAsStrings();
                c.ResolveConflictingActions(parameters =>
                {
                    return parameters.FirstOrDefault();
                });

                var apiKey = new ApiKeyScheme
                {
                    Name = "Authorization",
                    In = "header",
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
                    Type = "apiKey"
                };
                apiKey.Extensions.Add("TokenPath", "/api/Auth");

                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, apiKey);
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { JwtBearerDefaults.AuthenticationScheme, new string[] { } }
                });
            }));
        }
示例#17
0
        public static IServiceCollection AddODataSwaggerDocument(this IServiceCollection serviceCollection, Action <Info> info = null, Action <SwaggerGenOptions> options = null)
        {
            serviceCollection.AddSwaggerGen(x =>
            {
                Info settingInfo = new Info()
                {
                    Title = application.ApplicationName, Version = version, Description = application.RuntimeFramework.FullName
                };

                if (info != null)
                {
                    info(settingInfo);
                }
                x.DocumentFilter <ODataDocumentFilter>(serviceCollection.BuildServiceProvider());
                x.SwaggerDoc(version, settingInfo);
                if (options != null)
                {
                    options(x);
                }

                ApiKeyScheme apiKeyScheme = new ApiKeyScheme()
                {
                    Name        = "Authorization",
                    Description = "请在 Value 里填入=>  Bearer (拿到的Token)",
                    In          = "header",
                    Type        = "apiKey"
                };

                x.AddSecurityDefinition("Bearer", apiKeyScheme);
                x.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >()
                {
                    {
                        "Bearer",
                        Enumerable.Empty <string>()
                    }
                });

                x.IncludeXmlComments();
            });

            return(serviceCollection);
        }
示例#18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => { });

            services.AddApiVersioning(options =>
            {
                options.ApiVersionReader   = new QueryStringApiVersionReader();
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
                options.ReportApiVersions  = true;
            });

            string       tokenType    = null;
            ApiKeyScheme apiKeyScheme = null;

            string projectName        = "Vasconcellos Cars WebAPI";
            string projectDescription = "This project has the purpose of performing an exemplification";

            var swaggerConfigurationExtension = new SwaggerStartupConfigureServices(services, tokenType, apiKeyScheme)
                                                .SetProjectNameAndDescriptionn(projectName, projectDescription);
        }
示例#19
0
        /// <summary>
        /// Configures application services
        /// </summary>
        /// <param name="services">Services collection</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContextPool <DatabaseContext>(options =>
                                                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <DatabaseContext>()
            .AddDefaultTokenProviders();

            services.AddJwtBearerAuthentication(
                Configuration["Authentication:TokenSigningKey"],
                Configuration["Authentication:Issuer"],
                Configuration["Authentication:Audience"],
                60,
                1440);

            ConfigureAuthorizationPolicies(services);

            services.AddTransient <UserManager>();

            var apiKeyScheme = new ApiKeyScheme()
            {
                Description = "JWT Authorization Scheme",
                Name        = "Authorization",
                In          = "header",
                Type        = "apiKey"
            };

            services.AddSwaggerGen(i =>
            {
                i.SwaggerDoc("v1", new Info()
                {
                    Title = ApiName, Version = "v1"
                });
                i.AddSecurityDefinition("Bearer", apiKeyScheme);
            });
        }
示例#20
0
        private void ConfigureSwaggerService(IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                string basePath   = PlatformServices.Default.Application.ApplicationBasePath;
                string moduleName = GetType().GetTypeInfo().Module.Name.Replace(".dll", ".xml");
                string filePath   = Path.Combine(basePath, moduleName);
                string readme     = File.ReadAllText(Path.Combine(basePath, "README.md"));

                ApiKeyScheme scheme = Configuration.GetSection("ApiKeyScheme").Get <ApiKeyScheme>();
                options.AddSecurityDefinition("Authentication", scheme);

                Info info        = Configuration.GetSection("Info").Get <Info>();
                info.Description = readme;
                options.SwaggerDoc(info.Version, info);

                options.IncludeXmlComments(filePath);
                options.DescribeAllEnumsAsStrings();
                options.OperationFilter <ExamplesOperationFilter>();
                //options.DocumentFilter<HideInDocsFilter>();
            });
        }
        public static IServiceCollection AddSwagger(
            this IServiceCollection services)
        {
            Guard.NotNull(services, nameof(services));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("doc", new Info {
                    Title = "DetroitHarps API", Version = "v1"
                });
                c.DescribeAllEnumsAsStrings();
                c.DescribeStringEnumsInCamelCase();
                var apiScheme = new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter JWT with Bearer into field",
                    Name        = "Authorization",
                    Type        = "apiKey"
                };

                c.AddSecurityDefinition(
                    "Bearer",
                    apiScheme);
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", Enumerable.Empty <string>() },
                });
                c.EnableAnnotations();
                c.SchemaFilter <AssignPropertyRequiredFilter>();
                c.OperationFilter <FormFileSwaggerFilter>();
                c.MapType <FileResult>(() => new Schema
                {
                    Type = "file"
                });
            });

            return(services);
        }
示例#22
0
        public static IServiceCollection AddCustomSwaggerGen(this IServiceCollection services)
        {
            var apiKeyScheme = new ApiKeyScheme
            {
                Description = "JWT Authorization Scheme",
                Name        = "Authorization",
                In          = "header",
                Type        = "apiKey"
            };

            services.AddSwaggerGen(i =>
            {
                i.SwaggerDoc("v1", new Info {
                    Title = "Identity Api", Version = "v1"
                });
                i.AddSecurityDefinition("Bearer", apiKeyScheme);
                i.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } }
                });
            });
            return(services);
        }
示例#23
0
        public SwaggerGenConfiguration(
            IApiVersionDescriptionProvider?apiVersionDescriptionProvider,
            IOptions <SwaggerOptions>?swaggerOptions)
        {
            _apiVersionDescriptionProvider = apiVersionDescriptionProvider ?? throw new ArgumentNullException(nameof(apiVersionDescriptionProvider));
            if (swaggerOptions?.Value == default)
            {
                throw new ArgumentNullException(nameof(swaggerOptions));
            }

            _defaultScheme = swaggerOptions.Value.DefaultScheme;
            _apiKeyScheme  = new ApiKeyScheme
            {
                Name        = swaggerOptions.Value.ApiKeySchemeName,
                Description = swaggerOptions.Value.ApiKeySchemeDescription,
                In          = swaggerOptions.Value.ApiKeySchemeIn,
                Type        = swaggerOptions.Value.ApiKeySchemeType
            };
            _info = new Info
            {
                Title          = swaggerOptions.Value.Title,
                Description    = swaggerOptions.Value.Description,
                TermsOfService = swaggerOptions.Value.TermsOfService,
                Contact        = new Contact
                {
                    Name  = swaggerOptions.Value.ContactName,
                    Email = swaggerOptions.Value.ContactEmail,
                    Url   = $"{swaggerOptions.Value.ContactUrl}"
                },
                License = new License
                {
                    Name = swaggerOptions.Value.LicenseName,
                    Url  = $"{swaggerOptions.Value.LicenseUrl}"
                }
            };
        }
示例#24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <RouteOptions>(options =>
            {
                options.LowercaseUrls = true;
            });

            services.AddCors();

            services.AddMvc(o =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                o.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var key = Encoding.ASCII.GetBytes(Configuration["JwtKey"]);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddSwaggerGen(swagger =>
            {
                var info = new Info()
                {
                    Title       = SwaggerConfig.DocInfoTitle,
                    Version     = SwaggerConfig.DocInfoVersion,
                    Description = SwaggerConfig.DocInfoDescription,
                    Contact     = new Contact()
                    {
                        Name = SwaggerConfig.ContactName, Url = SwaggerConfig.ContactUrl
                    }
                };

                swagger.SwaggerDoc(SwaggerConfig.DocNameV1, info);

                var apiKeyScheme = new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                };

                swagger.AddSecurityDefinition("Bearer", apiKeyScheme);

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                swagger.AddSecurityRequirement(security);
            });

            services.AddDbContext <AlohaContext>(options =>
            {
                string connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb");
                string portNumber       = Regex.Match(connectionString, @"(?<=Data Source.+:)\d+")?.Value;

                if (portNumber != null && portNumber.Length > 0)
                {
                    connectionString += ";Port=" + portNumber;
                    connectionString  = connectionString.Replace(":" + portNumber, string.Empty);
                }

                options.UseMySql(connectionString);
            });

            // Services
            services.AddScoped <ISecurityService, SecurityService>();

            // Controllers
            services.AddScoped <SecurityController, SecurityController>();
            services.AddScoped <WorkersController, WorkersController>();
            services.AddScoped <WorkstationsController, WorkstationsController>();
            services.AddScoped <FloorsController, FloorsController>();
            services.AddScoped <OfficesController, OfficesController>();

            // Mappings
            services.AddScoped <IClassMapping <User, UserDto>, UserToUserDtoMapping>();
            services.AddScoped <IClassMapping <UserDto, User>, UserDtoToUserMapping>();
            services.AddScoped <IClassMapping <Worker, WorkerDto>, WorkerToWorkerDtoMapping>();
            services.AddScoped <IClassMapping <WorkerDto, Worker>, WorkerDtoToWorkerMapping>();
            services.AddScoped <IClassMapping <Workstation, WorkstationDto>, WorkstationToWorkstationDtoMapping>();
            services.AddScoped <IClassMapping <WorkstationDto, Workstation>, WorkstationDtoToWorkstationMapping>();
            services.AddScoped <IClassMapping <Floor, FloorDto>, FloorToFloorDtoMapping>();
            services.AddScoped <IClassMapping <FloorDto, Floor>, FloorDtoToFloorMapping>();
            services.AddScoped <IClassMapping <Office, OfficeDto>, OfficeToOfficeDtoMapping>();
            services.AddScoped <IClassMapping <OfficeDto, Office>, OfficeDtoToOfficeMapping>();

            // Updaters
            services.AddScoped <IEntityUpdater <Worker>, WorkerUpdater>();
            services.AddScoped <IEntityUpdater <Workstation>, WorkstationUpdater>();
            services.AddScoped <IEntityUpdater <Floor>, FloorUpdater>();
            services.AddScoped <IEntityUpdater <Office>, OfficeUpdater>();
        }
示例#25
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //JWT
            var jwtSetting = new JwtSettings();

            configuration.Bind(nameof(JwtSettings), jwtSetting);
            services.AddSingleton(jwtSetting);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSetting.Secret)),
                ValidateIssuer           = false,
                ValidateAudience         = false,
                RequireExpirationTime    = false,
                ValidateLifetime         = true,
                ClockSkew = TimeSpan.Zero
            };

            services.AddSingleton(tokenValidationParameters);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x => {
                x.SaveToken = true;
                x.TokenValidationParameters = tokenValidationParameters;
            });

            //swagger
            services.AddSwaggerGen(x =>
            {
                var swaggerInfo         = new Info();
                swaggerInfo.Description = "Note Store API";
                swaggerInfo.Version     = "v1";
                x.SwaggerDoc("v1", swaggerInfo);

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[0] }
                };

                var apiScheme         = new ApiKeyScheme();
                apiScheme.Description = "JWT authorization header using bearer scheme";
                apiScheme.Name        = "authorization";
                apiScheme.In          = "header";
                apiScheme.Type        = "apiKey";

                x.AddSecurityDefinition("Bearer", apiScheme);
                x.AddSecurityRequirement(security);
            });

            //identity service
            services.AddScoped <IIdentityService, IdentityService>();

            //origin URLS
            var originURLSettings = configuration.GetSection("OriginNames").Get <string[]>();

            //add cors
            services.AddCors(x => x.AddPolicy("MyPolicy", builder =>
            {
                builder.WithOrigins(originURLSettings)
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetPreflightMaxAge(TimeSpan.FromSeconds(86400));
            }));
        }
示例#26
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();

            var login = new Login();

            services.AddSingleton(login);

            var token = new Token();

            new ConfigureFromConfigurationOptions <Token>(Configuration.GetSection("TokenConfigurations")).Configure(token);
            services.AddSingleton(token);

            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearer =>
            {
                var paramsValidation = bearer.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = login.Chave;
                paramsValidation.ValidAudience            = token.Publico;
                paramsValidation.ValidIssuer              = token.Emissor;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("V1", new Info
                {
                    Title          = "2018 BPC World Cup Russia",
                    Version        = "v1",
                    Description    = "",
                    TermsOfService = "...",
                    Contact        = new Contact {
                        Name = "Lennon V. Alves Dias", Email = "*****@*****.**", Url = "http://www.lennonalves.com.br"
                    },
                    License = new License {
                        Name = "", Url = ""
                    }
                });

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } }
                };

                var apiKeyScheme = new ApiKeyScheme
                {
                    Description = "JWT Bearer Authentication",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                };

                s.AddSecurityDefinition("Bearer", apiKeyScheme);
                s.AddSecurityRequirement(security);
            });

            BaseContexto.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
            BaseContexto.DatabaseName     = Configuration.GetSection("MongoConnection:Database").Value;
            BaseContexto.IsSSL            = Convert.ToBoolean(this.Configuration.GetSection("MongoConnection:IsSSL").Value);

            services.AddMvc();

            RegisterServices(services);
        }
示例#27
0
        /// <summary>
        /// Extension method to configure swagger and add documentation
        /// </summary>
        /// <param name="services"></param>
        /// <param name="info"></param>
        /// <param name="apiKeyScheme"></param>
        /// <returns></returns>
        public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services, Info info, ApiKeyScheme apiKeyScheme)
        {
            info ??= default;
            apiKeyScheme ??= default;

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(info?.Version, new Info
                {
                    Version        = info?.Version,
                    Title          = info?.Title,
                    Description    = info?.Description,
                    TermsOfService = info?.TermsOfService,
                    Contact        = new Contact()
                    {
                        Name  = info?.Contact.Name,
                        Email = info?.Contact.Email,
                        Url   = info?.Contact.Url
                    }
                });

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = apiKeyScheme?.Description,
                    Name        = apiKeyScheme?.Name,
                    In          = apiKeyScheme?.In,
                    Type        = apiKeyScheme?.Type
                });

                var xmlFile = $"WideWorldImporters.API.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            return(services);
        }