Beispiel #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            AutoMapperContainer.Initialize();

            //Cors
            services.AddCors(options =>
                             options.AddPolicy(
                                 "AllowAll", p => {
                p.AllowAnyOrigin();
                p.AllowAnyMethod();
                p.AllowAnyHeader();
            }));

            services.Configure <MvcOptions>(options => {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
            });

            var connectionString = Configuration["connectionStrings:parcelamentoJuros"];

            if (Environment.IsProduction())
            {
                connectionString = Configuration["connectionStrings:parcelamentoJurosProd"];
            }

            services.AddDbContext <ParcelamentoJurosContext>(o => o.UseSqlServer(connectionString));

            services.AddScoped <IParcelaService, ParcelaService>();
            services.AddScoped <IParcelaRepository, ParcelaRepository>();
            services.AddScoped <ISimulacaoService, SimulacaoService>();
            services.AddScoped <ISimulacaoRepository, SimulacaoRepository>();

            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug(LogLevel.Information); //debug window
            //loggerFactory.AddProvider(new NLog.Extensions.Logging.NLogLoggerProvider());
            loggerFactory.AddNLog();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler(appBuilder =>
                {
                    appBuilder.Run(async context =>
                    {
                        var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                        if (exceptionHandlerFeature != null)
                        {
                            var logger = loggerFactory.CreateLogger("Global exception logger");
                            logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message);
                        }
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("Unexpected fault happened. Try again later.");
                    });
                });
            }

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer              = Configuration.GetSection("JWTSettings:Issuer").Value,
                    ValidAudience            = Configuration.GetSection("JWTSettings:Audience").Value,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JWTSettings:SecretKey").Value)),
                    ValidateLifetime         = true
                }
            });

            //// secretKey contains a secret passphrase only your server knows
            //var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
            //var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
            //var audience = Configuration.GetSection("JWTSettings:Audience").Value;
            //var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            //var tokenValidationParameters = new TokenValidationParameters
            //{
            //    ValidateIssuerSigningKey = true,
            //    IssuerSigningKey = signingKey,

            //    // Validate the JWT Issuer (iss) claim
            //    ValidateIssuer = true,
            //    ValidIssuer = issuer,

            //    // Validate the JWT Audience (aud) claim
            //    ValidateAudience = true,
            //    ValidAudience = audience
            //};
            //app.UseJwtBearerAuthentication(new JwtBearerOptions
            //{
            //    AutomaticAuthenticate = true,
            //    AutomaticChallenge = true,
            //    TokenValidationParameters = tokenValidationParameters
            //});

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AutomaticAuthenticate = true,
            //    AutomaticChallenge = true
            //});

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationScheme = "Cookies",
            //    AutomaticAuthenticate = true,
            //    AutomaticChallenge = true
            //});

            //app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            //{
            //    ClientId = "41326939717-76coj8vvak5t3e4ietrj0eirg3m1ginv.apps.googleusercontent.com",
            //    ClientSecret = "VU3yjPIPN0OEMEYTMm8nyncO",
            //    Authority = "https://accounts.google.com",
            //    ResponseType = OpenIdConnectResponseType.Code,
            //    GetClaimsFromUserInfoEndpoint = true,
            //    SaveTokens = true,
            //    Events = new OpenIdConnectEvents()
            //    {
            //        OnRedirectToIdentityProvider = (context) =>
            //        {
            //            if (context.Request.Path != "/api/values/external")
            //            {
            //                context.Response.Redirect("/api/values/external");
            //                context.HandleResponse();
            //            }

            //            return Task.FromResult(0);
            //        }
            //    }
            //});

            AutoMapperContainer.Initialize();

            // Enable Cors
            app.UseCors("MyPolicy");

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Trip API V1");
                c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }