public static void Configure(this CorsPolicyBuilder builder, CorsConfiguration configuration) { if (configuration.AllowedOrigins == null) { builder.AllowAnyOrigin(); } else { builder.WithOrigins(configuration.AllowedOrigins); } if (configuration.AllowedMethods == null) { builder.AllowAnyMethod(); } else { builder.WithMethods(configuration.AllowedMethods); } if (configuration.AllowedHeaders == null) { builder.AllowAnyHeader(); } else { builder.WithExposedHeaders(configuration.AllowedHeaders); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "dotnet_migration_toolkit", Version = "v1" }); }); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); //To allow access with any headers corsBuilder.AllowAnyMethod(); //Using HTTP Post or Get or other HTTP Methods corsBuilder.AllowAnyOrigin(); //To allow access for applications of any origin //To restrict the access from specific domain //corsBuilder.WithOrigins("https://domain:port"); // corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders("content-desposition"); services.AddCors(options => { options.AddPolicy("CorsPolicy", corsBuilder.Build()); }); services.AddSingleton <IMigrationService, MigrationService>(); }
public static CorsPolicyBuilder WithFusionHeaders(this CorsPolicyBuilder builder) => builder.WithExposedHeaders( FusionHeaders.RequestPublication, FusionHeaders.PublisherId, FusionHeaders.PublicationId, FusionHeaders.LTag, FusionHeaders.IsConsistent );
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var audienceConfig = Configuration.GetSection("Audience"); SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"])); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = audienceConfig["Iss"], ValidateAudience = true, ValidAudience = audienceConfig["Aud"], ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true, }; services.AddAuthentication(o => { o.DefaultAuthenticateScheme = "TestKey"; }) .AddJwtBearer("TestKey", x => { x.RequireHttpsMetadata = false; x.TokenValidationParameters = tokenValidationParameters; x.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); services.AddOcelot(Configuration); // ******************** // Setup CORS // ******************** var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders("Token-Expired"); services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); }
internal static void AddCORS(CorsPolicyBuilder builder, Configuration configData) { if (!string.IsNullOrEmpty(configData.AllowedOrigins)) { if (configData.AllowedOrigins == "*") { builder.AllowAnyOrigin(); } else { var allowedOrigins = configData.AllowedOrigins.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithOrigins(allowedOrigins); } } if (!string.IsNullOrEmpty(configData.AllowedMethods)) { if (configData.AllowedMethods == "*") { builder.AllowAnyMethod(); } else { var allowedMethods = configData.AllowedMethods.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithMethods(allowedMethods); } } if (!string.IsNullOrEmpty(configData.AllowedHeaders)) { if (configData.AllowedHeaders == "*") { builder.AllowAnyHeader(); } else { var allowedHeaders = configData.AllowedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries); builder.WithHeaders(allowedHeaders); } } if (!string.IsNullOrEmpty(configData.AllowedExposedHeaders)) { var allowedExposedHeaders = configData.AllowedExposedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries); if (allowedExposedHeaders.Any()) { builder.WithExposedHeaders(allowedExposedHeaders); } } if (configData.IsAllowedCredentials && configData.AllowedOrigins != "*") { builder.AllowCredentials(); } else { builder.DisallowCredentials(); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddSingleton(_config); //services.AddStormpath(); // services.AddScoped<TokenProviderMiddleware>(); services.AddIdentity <ProductUser, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 4; config.Password.RequireDigit = true; config.Password.RequireNonAlphanumeric = true; // config.Cookies.ApplicationCookie.LoginPath }) .AddEntityFrameworkStores <ProductContext>(); services.AddLogging(); services.AddDbContext <ProductContext>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <ProductContext>(); //services.AddCors(options => options.AddPolicy("AllowAll", x => x.AllowAnyOrigin())); services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:3000/")); }); // Define CORS Policy var corsBuilder = new CorsPolicyBuilder(); corsBuilder.WithHeaders("*"); corsBuilder.AllowAnyMethod(); corsBuilder.WithOrigins("http://localhost:3000"); //corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders().AllowAnyHeader(); corsBuilder.SetPreflightMaxAge(TimeSpan.FromSeconds(30)); services.AddCors(options => { options.AddPolicy("localhost", corsBuilder.Build()); }); // services.AddTransient<ProductContextSeedData>(); services.AddMvc(); }
/// <summary> /// Run cors setup. /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> public static void Run(IServiceCollection services, IConfiguration configuration) { // Cors configuration. var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.WithExposedHeaders("WWW-Authenticate"); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); // Add cors configuration to service configuration. services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); }
public void WithExposedHeaders_AddsExposedHeaders() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithExposedHeaders("exposed1", "exposed2"); // Assert var corsPolicy = builder.Build(); Assert.Equal(new List <string>() { "exposed1", "exposed2" }, corsPolicy.ExposedHeaders); }
public CorsPolicy Build() { CorsPolicyBuilder policy = new CorsPolicyBuilder(); if (this.AllowAnyOrigin) { policy.AllowAnyOrigin(); } else { policy.WithOrigins(this.Origins); } if (this.AllowAnyHeader) { policy.AllowAnyHeader(); } else { policy.WithHeaders(this.Headers); } if (this.AllowAnyMethod) { policy.AllowAnyMethod(); } else { policy.WithMethods(this.Methods); } if (this.SupportsCredentials) { policy.AllowCredentials(); } else { policy.DisallowCredentials(); } policy.WithExposedHeaders("content-disposition"); return(policy.Build()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { options.Filters.Add(new ApiExceptionFilter()); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Wevo.API", Version = "v1" }); }); var connectionString = Configuration.GetConnectionString("WevoConnection"); services.AddDbContext <WevoContext>(options => { options.UseSqlServer(connectionString); }); var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.WithExposedHeaders("X-Pagination"); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IRepositoryBase <User>, RepositoryBase <User> >(); }
private void ConfigureCorsPolicy(IServiceCollection services) { var sp = services.BuildServiceProvider(); var siteOptions = sp.GetService <SiteOptions>(); var corsPolicyBuilder = new CorsPolicyBuilder(); if (_currentEnvironment.IsProduction()) { corsPolicyBuilder.WithOrigins(siteOptions.Root); corsPolicyBuilder.WithExposedHeaders(Headers.XNewAuthToken); } else { corsPolicyBuilder.AllowAnyOrigin(); } corsPolicyBuilder.AllowAnyHeader(); //corsPolicyBuilder.WithMethods("GET","POST","PUT","DELETE"); corsPolicyBuilder.AllowAnyMethod(); // Constants.Headers.XNewRoles, corsPolicyBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy(CorsPolicyName, corsPolicyBuilder.Build()); }); }
public static CorsPolicyBuilder WithFusionHeaders(this CorsPolicyBuilder builder) => builder.WithExposedHeaders( FusionHeaders.RequestPublication, FusionHeaders.Publication );
public static CorsPolicyBuilder WithAbpExposedHeaders(this CorsPolicyBuilder corsPolicyBuilder) { return(corsPolicyBuilder.WithExposedHeaders("_AbpErrorFormat")); }
// 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); //Extrae El string de Conexion de appsettings.json, y se lo pone al modelo EmpresaDbContext.ConnectionString = Configuration.GetConnectionString("EmpresaDB"); //tambien lo guarda en ContextClass.. por si se necesita para algo mas.. Como el Dapper. ContextClass.ConnectionString = EmpresaDbContext.ConnectionString; //Configura la Validacion de Tokens para los request. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "Empresa/api", ValidAudience = "EmpresaApp", IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes("frase secreta para generar un array de bytes unico")) }; }); //Configura el CORS, que es lo que permite que el api sea comunicado por otras aplicaciones. como el front end //sino. se usara.. solo podria ser utilizado por algo corriendo el la misma pc y con el msimo puerto. var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); corsBuilder.WithExposedHeaders("filename"); services.Configure <RazorViewEngineOptions>(o => { // {2} is area, {1} is controller,{0} is the action o.ViewLocationFormats.Clear(); o.ViewLocationFormats.Add("/Content/Templates/{0}" + RazorViewEngine.ViewExtension); }); //se Encarga de que se respeten los nombres de las propiedades al conviertirse en jsons para los responses. //Si no estuviera, y mandaramos un objeto con la propiedad ID_Cliente, llegaria al frontend como iD_Cliente services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); //continua con la configuracion del CORS services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin")); }); string LibExtension = ""; if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { LibExtension = ".so"; } if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { LibExtension = ".dylib"; } if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { LibExtension = ".dll"; } var architectureFolder = (IntPtr.Size == 8) ? "64 bit" : "32 bit"; var wkHtmlToPdfPath = Path.Combine(Directory.GetCurrentDirectory(), $"Libraries\\libwkhtmltox\\{architectureFolder}\\libwkhtmltox" + LibExtension); CustomAssemblyLoadContext context = new CustomAssemblyLoadContext(); context.LoadUnmanagedLibrary(wkHtmlToPdfPath); // Add converter to DI services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools())); }
// 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); #region REGISTRO DE INTERFACES E CLASSES #region Atenção Básica services.AddTransient <IAgendaRepository, AgendaRepository>(); services.AddTransient <IAgendaCommand, AgendaCommandText>(); services.AddTransient <IAtendOdontoRepository, AtendOdontoRepository>(); services.AddTransient <IAtendOdontoCommand, AtendOdontoCommandText>(); services.AddTransient <IAtividadeColetivaRepository, AtividadeColetivaRepository>(); services.AddTransient <IAtividadeColetivaCommand, AtividadeColetivaCommandText>(); services.AddTransient <IConsumoAlimentarRepository, ConsumoAlimentarRepository>(); services.AddTransient <IConsumoAlimentarCommand, ConsumoAlimentarCommandText>(); services.AddTransient <Domain.Repositories.AtencaoBasica.IEstabelecimentoRepository, Domain.Infra.Repositories.AtencaoBasica.EstabelecimentoRepository>(); services.AddTransient <Domain.Commands.AtencaoBasica.IEstabelecimentoCommand, Domain.Queries.AtencaoBasica.EstabelecimentoCommandText>(); services.AddTransient <IEstabelecimentoSaudeRepository, EstabelecimentoSaudeRepository>(); services.AddTransient <IEstabelecimentoSaudeCommand, EstabelecimentoSaudeCommandText>(); services.AddTransient <IExameFisicoRepository, ExameFisicoRepository>(); services.AddTransient <IExameFisicoCommand, ExameFisicoCommandText>(); services.AddTransient <IFamiliaRepository, FamiliaRepository>(); services.AddTransient <IFamiliaCommand, FamiliaCommandText>(); services.AddTransient <IFichaComplementarRepository, FichaComplementarRepository>(); services.AddTransient <IFichaComplementarCommand, FichaComplementarCommandText>(); services.AddTransient <IGestaoFamiliaRepository, GestaoFamiliaRepository>(); services.AddTransient <IGestaoFamiliaCommand, GestaoFamiliaCommandText>(); services.AddTransient <IMicroareaRepository, MicroareaRepository>(); services.AddTransient <IMicroareaCommand, MicroareaCommandText>(); services.AddTransient <IProcedimentoAvulsoRepository, ProcedimentoAvulsoRepository>(); services.AddTransient <IProcedimentoAvulsoCommand, ProcedimentoAvulsoCommandText>(); services.AddTransient <IProcedimentoRepository, ProcedimentoRepository>(); services.AddTransient <IProcedimentoCommand, ProcedimentoCommandText>(); services.AddTransient <IVisitaDomiciliarRepository, VisitaDomiciliarRepository>(); services.AddTransient <IVisitaDomiciliarCommand, VisitaDomiciliarCommandText>(); services.AddTransient <IFamiliaRepository, FamiliaRepository>(); services.AddTransient <IFamiliaCommand, FamiliaCommandText>(); #endregion #region Cadastro services.AddTransient <IACSRepository, ACSRepository>(); services.AddTransient <IACSCommand, ACSCommandText>(); services.AddTransient <IBairroRepository, BairroRepository>(); services.AddTransient <IBairroCommand, BairroCommandText>(); services.AddTransient <ICidadaoRepository, CidadaoRepository>(); services.AddTransient <ICidadaoCommand, CidadaoCommandText>(); services.AddTransient <ICidadeRepository, CidadeRepository>(); services.AddTransient <ICidadeCommand, CidadeCommandText>(); services.AddTransient <IEquipeRepository, EquipeRepository>(); services.AddTransient <IEquipeCommand, EquipeCommandText>(); services.AddTransient <IEscolaRepository, EscolaRepository>(); services.AddTransient <IEscolaCommand, EscolaCommandText>(); services.AddTransient <IEstadoRepository, EstadoRepository>(); services.AddTransient <IEstadoCommand, EstadoCommandText>(); services.AddTransient <IFeriadoRepository, FeriadoRepository>(); services.AddTransient <IFeriadoCommand, FeriadoCommandText>(); services.AddTransient <IFornecedorRepository, FornecedorRepository>(); services.AddTransient <IFornecedorCommand, FornecedorCommandText>(); services.AddTransient <IFotoIndividuoRepository, FotoIndividuoRepository>(); services.AddTransient <IFotoIndividuoCommand, FotoIndividuoCommandText>(); services.AddTransient <IGestacaoRepository, GestacaoRepository>(); services.AddTransient <IGestacaoCommand, GestacaoCommandText>(); services.AddTransient <IIndividuoRepository, IndividuoRepository>(); services.AddTransient <IIndividuoCommand, IndividuoCommandText>(); services.AddTransient <ILogradouroRepository, LogradouroRepository>(); services.AddTransient <ILogradouroCommand, LogradouroCommandText>(); services.AddTransient <IPaisRepository, PaisRepository>(); services.AddTransient <Domain.Commands.Cadastro.IPaisCommand, PaisCommandText>(); services.AddTransient <IProfissaoRepository, ProfissaoRepository>(); services.AddTransient <Domain.Commands.Cadastro.IProfissaoCommand, ProfissaoCommandText>(); services.AddTransient <IProfissionalRepository, ProfissionalRepository>(); services.AddTransient <Domain.Commands.Cadastro.IProfissionalCommand, ProfissionalCommandText>(); services.AddTransient <IUnidadeRepository, UnidadeRepository>(); services.AddTransient <IUnidadeCommand, UnidadeCommandText>(); services.AddTransient <ISegUserRepository, SegUserRepository>(); services.AddTransient <ISegUsuarioCommand, SegUsuarioCommandText>(); services.AddTransient <IVersaoRepository, VersaoRepository>(); services.AddTransient <IVersaoCommand, VersaoCommandText>(); #endregion #region Endemias services.AddTransient <ICicloRepository, CicloRepository>(); services.AddTransient <ICicloCommand, CicloCommandText>(); services.AddTransient <IEspecimeRepository, EspecimeRepository>(); services.AddTransient <IEspecimeCommand, EspecimeCommandText>(); services.AddTransient <Domain.Repositories.Endemias.IEstabelecimentoRepository, Domain.Infra.Repositories.Endemias.EstabelecimentoRepository>(); services.AddTransient <Domain.Commands.Endemias.IEstabelecimentoCommand, Domain.Queries.Endemias.EstabelecimentoCommandText>(); services.AddTransient <IReportEndemiasRepository, ReportEndemiasRepository>(); services.AddTransient <IReportEndemiasCommand, ReportEndemiasCommandText>(); services.AddTransient <IResultadoAmostraRepository, ResultadoAmostraRepository>(); services.AddTransient <IResultadoAmostraCommand, ResultadoAmostraCommandText>(); services.AddTransient <IVisitaRepository, VisitaRepository>(); services.AddTransient <IVisitaCommand, VisitaCommandText>(); #endregion #region Imunização services.AddTransient <IAprazamentoRepository, AprazamentoRepository>(); services.AddTransient <IAprazamentoCommand, AprazamentoCommandText>(); services.AddTransient <ICalendarioBasicoRepository, CalendarioBasicoRepository>(); services.AddTransient <ICalendarioBasicoCommand, CalendarioBasicoCommandText>(); services.AddTransient <ICartaoVacinaRepository, CartaoVacinaRepository>(); services.AddTransient <ICartaoVacinaCommand, CartaoVacinaCommandText>(); services.AddTransient <IClasseRepository, ClasseRepository>(); services.AddTransient <IClasseCommand, ClasseCommandText>(); services.AddTransient <IDashboardRepository, DashboardRepository>(); services.AddTransient <IDashboardCommand, DashboardCommandText>(); services.AddTransient <IDoseRepository, DoseRepository>(); services.AddTransient <IDoseCommand, DoseCommandText>(); services.AddTransient <IEntradaProdutoRepository, EntradaProdutoRepository>(); services.AddTransient <IEntradaProdutoCommand, EntradaProdutoCommandText>(); services.AddTransient <IEntradaProdutoItemRepository, EntradaProdutoItemRepository>(); services.AddTransient <IEntradaProdutoItemCommand, EntradaProdutoItemCommandText>(); services.AddTransient <IEnvioRepository, EnvioRepository>(); services.AddTransient <IEnvioCommand, EnvioCommandText>(); services.AddTransient <IEstoqueRepository, EstoqueRepository>(); services.AddTransient <IEstoqueCommand, EstoqueCommandText>(); services.AddTransient <IEstrategiaRepository, EstrategiaRepository>(); services.AddTransient <IEstrategiaCommand, EstrategiaCommandText>(); services.AddTransient <IFabricanteRepository, FabricanteRepository>(); services.AddTransient <IFabricanteCommand, FabricanteCommandText>(); services.AddTransient <IFaixaEtariaRepository, FaixaEtariaRepository>(); services.AddTransient <IFaixaEtariaCommand, FaixaEtariaCommandText>(); services.AddTransient <IGrupoAtendimentoRepository, GrupoAtendimentoRepository>(); services.AddTransient <IGrupoAtendimentoCommand, GrupoAtendimentoCommandText>(); services.AddTransient <IImunobiologicoRepository, ImunobiologicoRepository>(); services.AddTransient <IImunobiologicoCommand, ImunobiologicoCommandText>(); services.AddTransient <ILoteRepository, LoteRepository>(); services.AddTransient <ILoteCommand, LoteCommandText>(); services.AddTransient <IMovImunobiologicoRepository, MovImunobiologicoRepository>(); services.AddTransient <IMovImunobiologicoCommand, MovImunobiologicoCommandText>(); services.AddTransient <IProdutoRepository, ProdutoRepository>(); services.AddTransient <IProdutoCommand, ProdutoCommandText>(); services.AddTransient <IProdutorRepository, ProdutorRepository>(); services.AddTransient <IProdutorCommand, ProdutorCommandText>(); services.AddTransient <IReportRepository, ReportRepository>(); services.AddTransient <IReportCommand, ReportCommandText>(); services.AddTransient <IUnidadeMedRepository, UnidadeMedRepository>(); services.AddTransient <IUnidadeMedCommand, UnidadeMedCommandText>(); services.AddTransient <IVacinaApresentacaoRepository, VacinaApresentacaoRepository>(); services.AddTransient <IVacinaApresentacaoCommand, VacinaApresentacaoCommandText>(); services.AddTransient <IViaAdmRepository, ViaAdmRepository>(); services.AddTransient <IViaAdmCommand, ViaAdmCommandText>(); #endregion #region Indicadores services.AddTransient <IIndicador1Repository, Indicador1Repository>(); services.AddTransient <IIndicador1Command, Indicador1CommandText>(); services.AddTransient <IIndicador2Repository, Indicador2Repository>(); services.AddTransient <IIndicador2Command, Indicador2CommandText>(); services.AddTransient <IIndicador2Repository, Indicador2Repository>(); services.AddTransient <IIndicador2Command, Indicador2CommandText>(); services.AddTransient <IIndicador3Repository, Indicador3Repository>(); services.AddTransient <IIndicador3Command, Indicador3CommandText>(); services.AddTransient <IIndicador4Repository, Indicador4Repository>(); services.AddTransient <IIndicador4Command, Indicador4CommandText>(); services.AddTransient <IIndicador5Repository, Indicador5Repository>(); services.AddTransient <IIndicador5Command, Indicador5CommandText>(); services.AddTransient <IIndicador6Repository, Indicador6Repository>(); services.AddTransient <IIndicador6Command, Indicador6CommandText>(); services.AddTransient <IIndicador7Repository, Indicador7Repository>(); services.AddTransient <IIndicador7Command, Indicador7CommandText>(); #endregion #region Segurança services.AddTransient <IPerfilRepository, PerfilRepository>(); services.AddTransient <IPerfilCommand, PerfilCommandText>(); services.AddTransient <IPerfilUsuarioRepository, PerfilUsuarioRepository>(); services.AddTransient <IPerfilUsuarioCommand, PerfilUsuarioCommandText>(); #endregion #region Prontuario services.AddTransient <IExameRepository, ExameRepository>(); services.AddTransient <IExameCommand, ExameCommandText>(); #endregion #endregion services.AddMvc().AddJsonOptions(opcoes => { //configuração para que valores nulos não sejam retornados na consulta opcoes.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); //funciona var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); var lista = "x-total-count"; corsBuilder.WithExposedHeaders(lista); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"])), ClockSkew = TimeSpan.Zero }); services.AddScoped <PermissaoUsuarioFilter>(); }
public void WithExposedHeaders_AddsExposedHeaders() { // Arrange var builder = new CorsPolicyBuilder(); // Act builder.WithExposedHeaders("exposed1", "exposed2"); // Assert var corsPolicy = builder.Build(); Assert.Equal(new List<string>() { "exposed1", "exposed2" }, corsPolicy.ExposedHeaders); }
public virtual async Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName) { ICorsPolicy[] loadedCorsPolicies = null; // Find cors policies manager. var corsPoliciesManager = context.RequestServices.GetService <ISiteCorsPolicyService>(); if (corsPoliciesManager == null) { throw new ArgumentException($"{nameof(ISiteCorsPolicyService)} is not found in service context."); } // Policy name is defined, find the entity. if (!string.IsNullOrWhiteSpace(policyName)) { var loadedCorsPolicy = await corsPoliciesManager.GetCorsPolicyAsync(policyName); if (loadedCorsPolicy != null) { loadedCorsPolicies = new[] { loadedCorsPolicy } } ; } else { loadedCorsPolicies = await corsPoliciesManager.GetInUseCorsPoliciesAsync(); } if (loadedCorsPolicies == null || loadedCorsPolicies.Length < 1) { return(null); } var appliedCorsPolicyBuilder = new CorsPolicyBuilder(); foreach (var loadedCorsPolicy in loadedCorsPolicies) { var allowedHeaders = loadedCorsPolicy.AllowedHeaders; if (allowedHeaders != null && allowedHeaders.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithHeaders(allowedHeaders); } var allowedOrigins = loadedCorsPolicy.AllowedOrigins; if (allowedOrigins != null && allowedOrigins.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithOrigins(allowedOrigins); } var allowedMethods = loadedCorsPolicy.AllowedMethods; if (allowedMethods != null && allowedMethods.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithMethods(allowedMethods); } var allowedExposedHeaders = loadedCorsPolicy.AllowedExposedHeaders; if (allowedExposedHeaders != null && allowedExposedHeaders.Length > 0) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.WithExposedHeaders(allowedExposedHeaders); } if (loadedCorsPolicy.AllowCredential) { appliedCorsPolicyBuilder = appliedCorsPolicyBuilder.AllowCredentials(); } } var builtPolicy = appliedCorsPolicyBuilder .Build(); return(builtPolicy); } #endregion }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { // Add services DI to app. AddServices(services); // Load jwt configuration from setting files. services.Configure <AppJwtModel>(Configuration.GetSection(AppConfigKeyConstant.AppJwt)); services.Configure <ApplicationSetting>(Configuration.GetSection(nameof(ApplicationSetting))); services.Configure <GoogleCredential>(Configuration.GetSection(AppConfigKeyConstant.GoogleCredential)); services.Configure <FacebookCredential>(Configuration.GetSection(AppConfigKeyConstant.FacebookCredential)); services.Configure <SendGridSetting>(Configuration.GetSection(AppConfigKeyConstant.AppSendGrid)); //services.Configure<PusherSetting>(Configuration.GetSection(nameof(PusherSetting))); services.Configure <CaptchaSetting>(Configuration.GetSection(nameof(CaptchaSetting))); // Build a service provider. var servicesProvider = services.BuildServiceProvider(); var jwtBearerSettings = servicesProvider.GetService <IOptions <AppJwtModel> >().Value; // Cors configuration. var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.WithExposedHeaders("WWW-Authenticate"); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); // Add cors configuration to service configuration. services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); services.AddOptions(); // This can be removed after https://github.com/aspnet/IISIntegration/issues/371 var authenticationBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme); authenticationBuilder.AddJwtBearer(o => { // You also need to update /wwwroot/app/scripts/app.js o.SecurityTokenValidators.Clear(); o.SecurityTokenValidators.Add(new JwtBearerValidator()); // Initialize token validation parameters. var tokenValidationParameters = new TokenValidationParameters(); tokenValidationParameters.ValidAudience = jwtBearerSettings.Audience; tokenValidationParameters.ValidIssuer = jwtBearerSettings.Issuer; tokenValidationParameters.IssuerSigningKey = jwtBearerSettings.SigningKey; #if DEBUG tokenValidationParameters.ValidateLifetime = false; #endif o.TokenValidationParameters = tokenValidationParameters; o.Events = new JwtBearerEvents { OnMessageReceived = context => { if (context.Request.Path.ToString() .StartsWith("/HUB/", StringComparison.InvariantCultureIgnoreCase)) { context.Token = context.Request.Query["access_token"]; } return(Task.CompletedTask); } }; }); // Add automaper configuration. services.AddAutoMapper(options => options.AddProfile(typeof(MappingProfile))); services.AddHttpClient(); // Add swagger. services.AddSwagger(); #region Signalr builder // Add signalr service. services.AddSignalR(); // Initialize signalr policy. //var signalrConnectionPolicy = services.AddAuthorization(x => x.AddPolicy(PolicyConstant.DefaultSignalRPolicyName, builder => { builder.RequireAuthenticatedUser() .AddRequirements(new SolidAccountRequirement()); })); services.AddAuthorization(x => x.AddPolicy(PolicyConstant.IsAdminPolicy, builder => { builder.AddRequirements(new RoleRequirement(new[] { UserRole.Admin })); })); #endregion #region Mvc builder // Construct mvc options. services.AddMvc(mvcOptions => { ////only allow authenticated users var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) #if !ALLOW_ANONYMOUS .AddRequirements(new SolidAccountRequirement()) #endif .Build(); mvcOptions.Filters.Add(new AuthorizeFilter(policy)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ; #endregion }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IUserRepository, UserRepository>(); services.AddSingleton <ITimeService, TimeService>(); services.AddSingleton <IConnectionCacheService, ConnectionCacheService>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSignalR(); // Build a service provider. var servicesProvider = services.BuildServiceProvider(); var jwtBearerSettings = servicesProvider.GetService <IOptions <JwtOption> >().Value; // Cors configuration. var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.WithExposedHeaders("WWW-Authenticate"); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); // Add cors configuration to service configuration. services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); }); services.AddOptions(); // This can be removed after https://github.com/aspnet/IISIntegration/issues/371 var authenticationBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme); // Initialize signalr policy. //var signalrConnectionPolicy = services.AddAuthorization(x => x.AddPolicy(PolicyConstant.DefaultSignalRPolicyName, builder => { builder.RequireAuthenticatedUser() .AddRequirements(new SolidAccountRequirement()); })); authenticationBuilder.AddJwtBearer(o => { // You also need to update /wwwroot/app/scripts/app.js o.SecurityTokenValidators.Clear(); o.SecurityTokenValidators.Add(new JwtBearerValidator()); // Initialize token validation parameters. var tokenValidationParameters = new TokenValidationParameters(); tokenValidationParameters.ValidAudience = jwtBearerSettings.Audience; tokenValidationParameters.ValidIssuer = jwtBearerSettings.Issuer; tokenValidationParameters.IssuerSigningKey = jwtBearerSettings.SigningKey; #if DEBUG tokenValidationParameters.ValidateLifetime = false; #endif o.TokenValidationParameters = tokenValidationParameters; o.Events = new JwtBearerEvents() { OnMessageReceived = context => { if (context.Request.Path.ToString().StartsWith("/HUB/", StringComparison.InvariantCultureIgnoreCase)) { context.Token = context.Request.Query["accessToken"]; } return(Task.CompletedTask); }, }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }