Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //   services.AddCors(options =>
            //options.AddPolicy("MyDomain",
            //builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

            services.AddMvc();
            //配置验证
            auth.ConfigureAuthService(services, Configuration);
            SwaggerConfig.ServicesConfig(services);
            return(IOCRegister.InitIoC(services, Configuration));
        }
Exemple #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            //Agrega el filtro de validación de datos indicandole el paquete donde se encuentran
            //todas las clases de validacion de datos
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add(new ValidationFilter());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <CycleValidator>());

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            /// Registra el contexto de la base de datos
            string connectionString = Configuration.GetConnectionString("DefaultConnection");

            IOCRegister.AddDBContext(services, connectionString);

            /// Registra todos los servicios
            IOCRegister.AddServices(services);

            /// Registra todos los repositorios
            IOCRegister.AddRepositories(services);

            /// Agrega los controladores
            services.AddControllers();


            //Agrega el cors para permitir peticiones desde el mismo ip local
            services.AddCors(Options =>
            {
                Options.AddPolicy("EnableCORS", builder =>
                {
                    builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .WithExposedHeaders(HeaderNames.ContentDisposition)
                    .WithOrigins("http://192.168.0.102:4200", "http://192.168.0.100:4200")
                    .Build();
                });
            });
        }
Exemple #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <ICoworkingDbContext, CoworkingDbContext>();
            services.AddDbContext <CoworkingDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));

            IOCRegister.AddRegistration(services);
            SwaggerConfing.AddRegistration(services);

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5000/";
                options.RequireHttpsMetadata = false;
                options.ApiName = "api1";
            });

            services.AddMvc();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //Agrega el filtro de validación de datos indicandole el paquete donde se encuentran
            //todas las clases de validacion de datos
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
                options.Filters.Add(new ValidationFilter());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <CycleValidator>());

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            /// Registra el contexto de la base de datos
            string connectionString = Configuration.GetConnectionString("DefaultConnection");

            IOCRegister.AddDBContext(services, connectionString);

            /// Registra todos los servicios
            IOCRegister.AddServices(services);

            /// Registra todos los repositorios
            IOCRegister.AddRepositories(services);

            /// Agrega los controladores
            services.AddControllers();

            //Autoriza el acceso a las rutas según el role
            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults
                                                                       .AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            //Valida el token
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ClockSkew                = TimeSpan.Zero,
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(
                        Encoding.ASCII.GetBytes(Configuration.GetValue <string>("Jwt:Secret")))
                };
            });

            //Agrega el cors para permitir peticiones desde el mismo ip local
            services.AddCors(Options =>
            {
                Options.AddPolicy("EnableCORS", builder =>
                {
                    builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders(HeaderNames.ContentDisposition)
                    .AllowAnyOrigin()
                    .Build();
                });
            });
        }
Exemple #5
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var urls = "http://localhost:6901/";

            services.AddCors(options =>
                             options.AddPolicy("MyDomain",
                                               builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

            //读取配置文件
            var audienceConfig            = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64      = audienceConfig["Secret"];
            var keyByteArray              = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey                = new SymmetricSecurityKey(keyByteArray);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = audienceConfig["Issuer"],   //发行人
                ValidateAudience      = true,
                ValidAudience         = audienceConfig["Audience"], //订阅人
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
                RequireExpirationTime = true,
            };
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //这个集合模拟用户权限表,可从数据库中查询出来
            var permission = new List <Permission> {
                new Permission {
                    Url = "/", Name = "admin"
                },
                new Permission {
                    Url = "/api/values", Name = "admin"
                },
                new Permission {
                    Url = "/", Name = "system"
                },
                new Permission {
                    Url = "/api/values1", Name = "system"
                }
            };
            //如果第三个参数,是ClaimTypes.Role,上面集合的每个元素的Name为角色名称,如果ClaimTypes.Name,即上面集合的每个元素的Name为用户名
            var permissionRequirement = new PermissionRequirement(
                "/api/denied", permission,
                ClaimTypes.Role,
                audienceConfig["Issuer"],
                audienceConfig["Audience"],
                signingCredentials,
                expiration: TimeSpan.FromSeconds(10)
                );

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission",
                                  policy => policy.Requirements.Add(permissionRequirement));
            }).AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //不使用https
                o.RequireHttpsMetadata      = false;
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        if (context.Request.Path.Value.ToString() == "/api/logout")
                        {
                            var token = ((context as TokenValidatedContext).SecurityToken as JwtSecurityToken).RawData;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            //注入授权Handler
            services.AddSingleton <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);
            services.AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            });
            SwaggerConfig.AddSwaggerGen(services);
            services.AddMemoryCache();                                                                                   //启用MemoryCache
            services.Configure <MemoryCacheEntryOptions>(
                options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5))                            //设置MemoryCache缓存有效时间为5分钟。
            .Configure <DistributedCacheEntryOptions>(option =>
                                                      option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)); //设置Redis缓存有效时间为5分钟。
            return(IOCRegister.InitIoC(services, Configuration));
        }