Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // services.AddDbContext<EFCoreWebDemoContext>();
            //services.AddTransient<DbInitializer>();

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                var multiVersionReader    = new HeaderApiVersionReader("x-version");
                options.ApiVersionReader  = multiVersionReader;
                options.DefaultApiVersion = new ApiVersion(1, 0);
            });
            services.AddMvc();
            services.AddSingleton <IConfiguration>(Configuration);
            //      services.AddScoped<IStarWarsService,StarWarsMockService>();
            var container = new ContainerBuilder();

            container.Populate(services);
            container.RegisterModule <taller.Infraestructure.AutofacModules.ServicesModules>();
            return(new AutofacServiceProvider(container.Build()));
        }
Exemplo n.º 2
0
 public static void ConfigureApiVersioning(this IServiceCollection services)
 {
     services.AddApiVersioning(options =>
     {
         options.ReportApiVersions = true;
         options.AssumeDefaultVersionWhenUnspecified = true;
         var multiVersionReader    = new HeaderApiVersionReader("x-version");
         options.ApiVersionReader  = multiVersionReader;
         options.DefaultApiVersion = new ApiVersion(1, 0);
     });
 }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Dependency Injection
            services.AddScoped <IUserService, UserService>();
            //Entity FrameWork - Context Injection
            services.AddDbContext <NexusContext>(options => options.UseSqlServer(GlobalSettings.ConnectionString));
            //JWT Authetication
            var key = Encoding.ASCII.GetBytes(GlobalSettings.Secret);

            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.AddControllers();
            //SWAGGER/OPENAPI
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(GlobalSettings.Api_Version, new OpenApiInfo {
                    Title = "NexusApi", Version = $"V{GlobalSettings.Api_Version}"
                });
            });

            //MVC Versioning
            services.AddApiVersioning(v =>
            {
                v.AssumeDefaultVersionWhenUnspecified = true;
                v.ReportApiVersions    = true;
                var multiVersionReader = new HeaderApiVersionReader("api-version");
                v.ApiVersionReader     = multiVersionReader;
                v.DefaultApiVersion    = new ApiVersion(Convert.ToInt32(GlobalSettings.Api_Version), 0);
            });
        }
Exemplo n.º 4
0
        public static void AddConfiguredVersioning(this IServiceCollection services)
        {
            var versionReader = new HeaderApiVersionReader("version");

            services.AddApiVersioning(
                options =>
            {
                options.ReportApiVersions = true;
                options.ApiVersionReader  = versionReader;
            });
            services.AddVersionedApiExplorer(
                options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.ApiVersionParameterSource = versionReader;
            });
        }
Exemplo 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.AddDbContext <EFDataContext>(ServiceLifetime.Scoped);
            services.AddScoped <ICampRepository, CampRepository>();
            services.AddTransient <CampDbInitializer>();
            services.AddTransient <CampIdentityInitializer>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddAutoMapper();

            //Configure Identity
            services.AddIdentity <CampUser, IdentityRole>()
            .AddEntityFrameworkStores <EFDataContext>()
            .AddDefaultTokenProviders();



            //Token based authentication
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(option =>
            {
                option.SaveToken                 = true;
                option.RequireHttpsMetadata      = false;
                option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Tokens:Audience"],
                    ValidIssuer      = Configuration["Tokens:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });



            //For CORS
            services.AddCors(cfg =>
            {
                cfg.AddPolicy("Wildermuth", bldr =>
                {
                    bldr.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://mahedee.net");
                });

                cfg.AddPolicy("AnyGET", bldr =>
                {
                    bldr.AllowAnyHeader()
                    .WithMethods("GET")
                    .AllowAnyOrigin();
                });
            });


            services.AddAuthorization(cfg =>
            {
                cfg.AddPolicy("SuperUsers", p => p.RequireClaim("SuperUser", "True"));
            });


            services.AddMvc(opt =>
            {
                if (!_env.IsProduction())
                {
                    opt.SslPort = 44388;
                }
                opt.Filters.Add(new RequireHttpsAttribute());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling =
                    ReferenceLoopHandling.Ignore;
            });


            services.AddApiVersioning(cgf =>
            {
                cgf.DefaultApiVersion = new ApiVersion(1, 1);
                cgf.AssumeDefaultVersionWhenUnspecified = true;
                cgf.ReportApiVersions = true;
                var rdr = new HeaderApiVersionReader("ver");
                rdr.HeaderNames.Add("X-MyCodeCamp-Version");
                cgf.ApiVersionReader = rdr;


                cgf.Conventions.Controller <TalksController>()
                .HasApiVersion(new ApiVersion(1, 0))
                .HasApiVersion(new ApiVersion(1, 1))
                .HasApiVersion(new ApiVersion(2, 0))
                .Action(m => m.Post(default(string), default(int), default(TalkModel)))
                .MapToApiVersion(new ApiVersion(2, 0));
            });



            /*
             *          services.ConfigureApplicationCookie(options =>
             *          {
             *              options.Events.OnRedirectToLogin = context =>
             *              {
             *                  if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == 200)
             *                  {
             *                      context.Response.StatusCode = 401;
             *                  }
             *
             *                  return Task.CompletedTask;
             *              };
             *
             *              options.Events.OnRedirectToAccessDenied = context =>
             *              {
             *                  if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == 200)
             *                  {
             *                      context.Response.StatusCode = 403;
             *                  }
             *
             *                  return Task.CompletedTask;
             *              };
             *          });
             *
             *
             */
        }
Exemplo n.º 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            //LD we need to make available the "ConfigurationBuilder" service for any future use.
            services.AddSingleton(Configuration);

            //LD STEP33 now we add the service. Usually for EntityFramework
            //request we use "AddScoped"
            services.AddScoped <ICampRepository, CampRepository>();

            //LD STEP44 the repository above need to have INJECTED the DBCONTEXT "CampContext"
            services.AddDbContext <CampContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LdConnectionStringMyCodeCamp2")));


            //LD STEP55 we add the dependency to a class in order to SEED the database
            services.AddTransient <CampDbInitializer>();

            //LD STEP27
            services.AddTransient <CampIdentityInitializer>();

            ////LD STEP888
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddAutoMapper();

            //LD STEP51
            services.AddMemoryCache();

            //LD STEPdist1
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = "localhost";
                options.InstanceName  = "ThisWebsite";
            });

            //LD STEP19
            services.AddIdentity <CampUser, IdentityRole>().AddEntityFrameworkStores <CampContext>();

            //LD STEP21
            services.Configure <IdentityOptions>(config =>
            {
                config.Cookies.ApplicationCookie.Events = //LD STEP22
                                                          new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = (ctx) =>
                    {
                        //LD if the call is from an API and we are going to redirect to the login page, just return error 401
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }

                        return(Task.CompletedTask);
                    },
                    OnRedirectToAccessDenied = (ctx) =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 403;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            //LD STEP38
            services.AddApiVersioning(cfg =>
            {
                cfg.DefaultApiVersion = new ApiVersion(1, 1);
                cfg.AssumeDefaultVersionWhenUnspecified = true;
                cfg.ReportApiVersions = true; //LD this will send back in the header the supported api versions
                //LD STEP44
                var rdr = new HeaderApiVersionReader("ver");
                //rdr.HeaderNames.Add("X-MyCodeCamp-Version");
                //cfg.ApiVersionReader = rdr;

                //LD STEP45
                //cfg.Conventions.Controller<TalksController>()
                //  .HasApiVersion(new ApiVersion(1, 0))
                //  .HasApiVersion(new ApiVersion(1, 1))
                //  .HasApiVersion(new ApiVersion(2, 0))
                //  .Action(m => m.Post(default(string), default(int), default(TalkModel)))
                //    .MapToApiVersion(new ApiVersion(1, 1));
            });


            //LD STEP13
            //services.AddCors();

            //LD STEP15
            services.AddCors(cfg =>
            {
                cfg.AddPolicy("Wildermuth", bldr =>
                {
                    bldr.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://wildermuth.com");
                });

                cfg.AddPolicy("AnyGET", bldr =>
                {
                    bldr.AllowAnyHeader()
                    .WithMethods("GET")
                    .AllowAnyOrigin();
                });
            });

            //LD STEP36
            //LD adding the policy that can be called from any action controller
            services.AddAuthorization(cfg =>
            {
                cfg.AddPolicy("SuperUsers", p => p.RequireClaim("SuperUser", "True"));
            });


            // Add framework services.
            services.AddMvc(opt =>
            {
                if (!_env.IsProduction())
                {
                    opt.SslPort = 44342; //LD same port we see in configuration
                }
                //LD STEP12
                opt.Filters.Add(new RequireHttpsAttribute());
            })
            .AddJsonOptions(opt =>   //LD STEP88 setting to avoid ciclic references of clesses when we use json
            {
                opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
        }