Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureService.ConfigureDependeciesService(services);
            ConfigureRepository.ConfigureDependeciesRepository(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Esempio n. 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddMemoryCache();
            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
            services.AddResponseCompression(option => { option.Providers.Add <GzipCompressionProvider>(); });

            ConfigureService.ConfigureDependeciesService(services);
            ConfigureRepository.ConfigureDependeciesRepository(services);

            string conStr = Configuration.GetConnectionString("DefaultConnection");

            BaseContextHelpers.SetConnectionStr(conStr);

            var serverVersion = new MySqlServerVersion(new Version(5, 7, 17));

            services.AddDbContextPool <BaseContext>(
                dbContextOptions => dbContextOptions
                .UseMySql(conStr, serverVersion)
                .EnableDetailedErrors()
                );

            var ver = ServerVersion.AutoDetect(conStr);

            services.AddDbContext <BaseContext>(options => options.UseMySql(conStr, ver));

            //CORS

            string[] hostPermitido = new string[] { "*", "http://localhost:3000", "http://localhost:3001" };

            services.AddCors(options =>
            {
                options.AddPolicy("PolicyCORS", builder => builder
                                  .WithOrigins(hostPermitido)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  );
            });
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureService.ConfigureDependeciesService(services);
            ConfigureRepository.ConfigureDependeciesRepository(services);

            var signingConfigurations = new SigningConfiguration();

            services.AddSingleton(signingConfigurations);

            var tokenConfiguration = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfiguration"))
            .Configure(tokenConfiguration);

            services.AddSingleton(tokenConfiguration);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = signingConfigurations.Key;
                paramsValidation.ValidAudience            = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer              = tokenConfiguration.Issuer;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

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

            services.AddControllers();
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Api-Restful-DDD",
                    Description = "DDD Architecture",
                    Contact     = new OpenApiContact
                    {
                        Name  = "Carlos Cunha",
                        Email = "*****@*****.**"
                    }
                });

                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "Acess Token",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });

                x.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        }, new List <string>()
                    }
                });
            });
        }
Esempio n. 4
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_2);
            services.AddDbContext <MultiLingoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MultiLingoDb"), b => b.MigrationsAssembly("MultiLingo.Infra")));


            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);
            var tokenConfigurations = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfigurations")).Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);
            //DI
            ConfigureService.ConfigureDependeciesService(services);
            ConfigureRepository.ConfigureDependeciesRepository(services);

            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = signingConfigurations.Key;
                paramsValidation.ValidAudience            = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer              = tokenConfigurations.Issuer;
                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(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MultiLingo API", Version = "v1"
                });


                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "Entre com o token JWT",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                x.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        }, new List <string>()
                    }
                });
            });
        }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            ConfigureService.ConfigureDependeciesService(services);
            ConfigureRepository.ConfigureDependeciesRepository(services);
            services.AddScoped <WebSocketHandler, ChatMessageHandler>();

            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfigurations();

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

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = signingConfigurations.Key;
                paramsValidation.ValidAudience            = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer              = tokenConfigurations.Issuer;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;

                bearerOptions.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        //verificar se o token esta valido
                        return(Task.CompletedTask);
                    }
                };
            });

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


            //Swagger
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "API - Comunicação de Dados",
                    Version     = "v1",
                    Description = "Trabalho prático"
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization utilizando o scheme Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        }, new string[] {}
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddControllers();

            services.AddWebSocketManager();
        }
Esempio n. 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Usar o DBContextpooling nos permite emitir uma DBContext instância para cada campo que precisa de uma. Mas em vez de criar uma DBContextinstância para cada campo e jogá-la fora depois de usá-la, estamos alugando para que os campos e solicitações possam reutilizá-la.
            //Por padrão, o DBContextpool manterá 128 DBContextinstâncias em seu pool.
            services.AddDbContextPool <NCContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            //AddScoped: Garante que tenha apenas um Datacontext por requisição. Ele abre a conexão, processa a requisção, retorna e fecha a conexão automaticamente.
            services.AddScoped <NCContext, NCContext>();

            //Converte em bytes a chave secreta
            var key = Encoding.ASCII.GetBytes(Settings.Secret);

            //Curso 7196 do balta.io ensina autenticação com o google
            #region Authentication
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = "audience",
                    ValidIssuer         = "issuer",
                    RequireSignedTokens = false,
                    IssuerSigningKey    =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret"))
                };

                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;
            });

            #endregion

            services.AddDbContext <NCContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            ConfigureService.ConfigureDependecyService(services);               //adicionado essa linha
            ConfigureRepository.ConfigureDependeciesRepository(services);

            #region GraphQL

            //Para usar DataLoader com Hot Chocolate
            services.AddDataLoaderRegistry();

            services.AddGraphQL(s => SchemaBuilder.New()
                                .AddServices(s)

                                .AddType <PessoaExternaType>()

                                .AddQueryType(d => d.Name("Query"))
                                .AddType <PessoaExternaQuery>()

                                .AddMutationType(d => d.Name("Mutation"))
                                .AddType <UsuarioPessoaExternaMutation>()

                                .Create());


            #endregion
        }