示例#1
0
 /// <summary>
 /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
 /// </summary>
 /// <param name="app"></param>
 /// <param name="env"></param>
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
         app.UseBrowserLink();
     }
     else
     {
         app.UseExceptionHandler("/Home/Error");
     }
     app.UseStaticFiles();
     app.UseMvc();
     SwaggerConfig.UseSwaggerUI(app);
 }
示例#2
0
        public void Configuration(IAppBuilder app)
        {
            HostingEnvironment.RegisterVirtualPathProvider(new EntityViewPathProvider());
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration, RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            SwaggerConfig.Register();

            string contentDistPath = Path.Combine(BennerConfiguration.WesFolder, "content", "dist");

            new FileHashGenerator(contentDistPath).HashMinifiedFiles();

            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(DependencyContainer.InternalKernel);

            var startup20 = this as IStartup20;

            if (startup20 != null)
            {
                startup20.Configuration20(app);
            }

            var startup30 = this as IStartup30;

            if (startup30 != null)
            {
                startup30.Configuration30(app);
            }

            var startup40 = this as IStartup40;

            if (startup40 != null)
            {
                startup40.Configuration40(app);
            }

            var startup50 = this as IStartup50;

            if (startup50 != null)
            {
                startup50.Configuration50(app);
            }

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
示例#3
0
        public void Configuration(IAppBuilder app)
        {
            HostingEnvironment.RegisterVirtualPathProvider(new EntityViewPathProvider());
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration, RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            SwaggerConfig.Register();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var startup20 = this as IStartup20;

            if (startup20 != null)
            {
                startup20.Configuration20(app);
            }

            var startup30 = this as IStartup30;

            if (startup30 != null)
            {
                startup30.Configuration30(app);
            }

            var startup40 = this as IStartup40;

            if (startup40 != null)
            {
                startup40.Configuration40(app);
            }

            var startup50 = this as IStartup50;

            if (startup50 != null)
            {
                startup50.Configuration50(app);
            }
        }
示例#4
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));
        }