Exemple #1
0
        public void Ctor_WithUnicodeRanges()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);

            // Act & assert
            Assert.Equal("a", encoder.HtmlEncode("a"));
            Assert.Equal("\u00E9", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
            Assert.Equal("\u2601", encoder.HtmlEncode("\u2601" /* CLOUD */));
        }
Exemple #2
0
        public void Ctor_WithNoParameters_DefaultsToBasicLatin()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder();

            // Act & assert
            Assert.Equal("a", encoder.HtmlEncode("a"));
            Assert.Equal("é", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
            Assert.Equal("☁", encoder.HtmlEncode("\u2601" /* CLOUD */));
        }
Exemple #3
0
        public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);

            // Act
            string retVal = encoder.HtmlEncode(input);

            // Assert
            Assert.Equal(expected, retVal);
        }
        public void Ctor_WithCodePointFilter()
        {
            // Arrange
            var filter = new CodePointFilter().AllowCharacters("ab").AllowCharacters('\0', '&', '\uFFFF', 'd');
            HtmlEncoder encoder = new HtmlEncoder(filter);

            // Act & assert
            Assert.Equal("a", encoder.HtmlEncode("a"));
            Assert.Equal("b", encoder.HtmlEncode("b"));
            Assert.Equal("c", encoder.HtmlEncode("c"));
            Assert.Equal("d", encoder.HtmlEncode("d"));
            Assert.Equal("�", encoder.HtmlEncode("\0")); // we still always encode control chars
            Assert.Equal("&", encoder.HtmlEncode("&")); // we still always encode HTML-special chars
            Assert.Equal("", encoder.HtmlEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
        }
Exemple #5
0
        public void Default_EquivalentToBasicLatin()
        {
            // Arrange
            HtmlEncoder controlEncoder = new HtmlEncoder(UnicodeRanges.BasicLatin);
            HtmlEncoder testEncoder = HtmlEncoder.Default;

            // Act & assert
            for (int i = 0; i <= Char.MaxValue; i++)
            {
                if (!IsSurrogateCodePoint(i))
                {
                    string input = new String((char)i, 1);
                    Assert.Equal(controlEncoder.HtmlEncode(input), testEncoder.HtmlEncode(input));
                }
            }
        }
Exemple #6
0
 public void HtmlEncode_NullInput_Throws()
 {
     // Arrange
     HtmlEncoder encoder = new HtmlEncoder();
     Assert.Throws<ArgumentNullException>(() => { encoder.HtmlEncode(null); });
 }
Exemple #7
0
        public void HtmlEncode_EmptyStringInput_ReturnsEmptyString()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder();

            // Act & assert
            Assert.Equal("", encoder.HtmlEncode(""));
        }
Exemple #8
0
        public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);

            // Act & assert - BMP chars
            for (int i = 0; i <= 0xFFFF; i++)
            {
                string input = new String((char)i, 1);
                string expected;
                if (IsSurrogateCodePoint(i))
                {
                    expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
                }
                else
                {
                    if (input == "<") { expected = "&lt;"; }
                    else if (input == ">") { expected = "&gt;"; }
                    else if (input == "&") { expected = "&amp;"; }
                    else if (input == "\"") { expected = "&quot;"; }
                    else
                    {
                        bool mustEncode = false;
                        if (i == '\'' || i == '+')
                        {
                            mustEncode = true; // apostrophe, plus
                        }
                        else if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
                        {
                            mustEncode = true; // control char
                        }
                        else if (!UnicodeHelpers.IsCharacterDefined((char)i))
                        {
                            mustEncode = true; // undefined (or otherwise disallowed) char
                        }

                        if (mustEncode)
                        {
                            expected = String.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
                        }
                        else
                        {
                            expected = input; // no encoding
                        }
                    }
                }

                string retVal = encoder.HtmlEncode(input);
                Assert.Equal(expected, retVal);
            }

            // Act & assert - astral chars
            for (int i = 0x10000; i <= 0x10FFFF; i++)
            {
                string input = Char.ConvertFromUtf32(i);
                string expected = String.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
                string retVal = encoder.HtmlEncode(input);
                Assert.Equal(expected, retVal);
            }
        }
Exemple #9
0
 public void WriteTo(TextWriter writer, HtmlEncoder encoder)
 {
 }
Exemple #10
0
 public TagHelperScopeInfo(ViewBuffer buffer, HtmlEncoder encoder, TextWriter writer)
 {
     Buffer  = buffer;
     Encoder = encoder;
     Writer  = writer;
 }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public override void Initialize(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorPagesOptions(opts =>
            {
                opts.Conventions.AddPageRoute("/admin/login", "admin");
            });

            //services.AddDbContextPool<ABDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),100);
            services.AddDbContext <ABDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //程序集依赖注入
            services.AddAssembly("AiBao.Services");

            //ApiController 的模型验证错误返回
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var res = context.ModelState.Where(e => e.Value.Errors.Any())
                              .Select(e => new ApiJsonResult()
                    {
                        code = 1005,
                        msg  = e.Value.Errors.First().ErrorMessage
                    }).FirstOrDefault();
                    return(new OkObjectResult(res));
                };
            });
            services.AddSingleton <IWebHelper, WebHelper>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IMailProvide, MailProvide>();
            services.AddSingleton <IMediaItemStorage, MediaItemStorage>();
            services.AddScoped <SiteWorkContext>();
            services.AddScoped <SysUserAuthentication>();
            services.AddScoped <WorkContext>();

            //启用redis或者内存缓存,默认使用内存缓存
            services.AddRedisOrMemoryCache(Configuration);
            //
            //Mapper.Initialize(x => x.AddProfile<MappingProfile>());
            services.AddAutoMapper(opts =>
            {
                //opts.AddProfile<MappingProfile>();
            });

            //启用JWT
            services.AddJwt(_hosting);

            //API版本
            services.AddApiVersioning(opts =>
            {
                opts.AssumeDefaultVersionWhenUnspecified = true;
            });

            //中文编码 https://docs.microsoft.com/zh-cn/aspnet/core/security/cross-site-scripting?view=aspnetcore-2.1#customizing-the-encoders
            services.AddSingleton <HtmlEncoder>(HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                                                                          UnicodeRanges.CjkUnifiedIdeographs }));

            //Cookie登陆状态保存设置
            services.AddAuthentication(o =>
            {
                o.DefaultSignInScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts =>
            {
                opts.Cookie.HttpOnly = true;
                opts.LoginPath       = "/admin";
            });
        }
Exemple #12
0
 public void TestInvalidEntity()
 {
     var encoder = new HtmlEncoder();
     Assert.AreEqual("&blah;", encoder.Decode("&blah;"));
 }
Exemple #13
0
        /// <summary>
        ///  This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            // Encoding encoding = Encoding.GetEncoding("GB2312");
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigin", builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()

                    ;
                });
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc(option =>
            {
                option.Filters.Add(typeof(SingleLoginFilter));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            //
            // var connection = "Server=39.97.180.241;Database=ef;User=root;Password=yj704104;";

            //Allow Zero Datetime=True
            var connection = "Data Source=47.100.63.224;Database=test3;User Id=root;Password=8US7DJ3WB5v;Convert Zero Datetime=True;Allow User Variables=True;CharSet=utf8";

            // var zcUrl = "Data Source=101.132.96.199;Database=clkrzc;User Id=root;Password=123456;Convert Zero Datetime=True;Allow User Variables=True; ";
            //var connection = @"Server=localhost;Initial Catalog=master;Integrated Security=True";
            services
            .AddDbContext <OAContext>(options => options.UseMySql(connection))
            .AddDbContext <SysContext>(options => options.UseMySql(connection))

            ;
            //解决中文被编码
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddHttpClient();
            services.AddSwaggerDocument(config =>
            {
                config.Version = "v1";
                config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT"));
                config.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT", new SwaggerSecurityScheme
                {
                    Type        = SwaggerSecuritySchemeType.ApiKey,
                    Name        = "Authorization",
                    In          = SwaggerSecurityApiKeyLocation.Header,
                    Description = "Type into the textbox: Bearer {your JWT token}. You can get a JWT token from /Authorization/Authenticate."
                }));

                // Post process the generated document
                config.PostProcess = d =>
                {
                    d.Info.Title = "创联科技Sass服务";
                    d.Consumes   = (ICollection <string>) new List <string> {
                        "application/x-www-form-urlencoded"
                    };
                    d.Info.Description = "创联凯尔Sass服务平台,Oa,金融";
                    d.Info.Contact     = new SwaggerContact {
                        Url = "https://www.yuque.com/jieyang/cucr-sass", Name = "在线开发文档", Email = "*****@*****.**"
                    };
                };
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <ICommonService, CommonService>();
            services.AddSingleton <IUserService, UserService>();
            services.AddSingleton <ISmsService, SmsService>();
            services.AddSingleton <IIncardService, IncardService>();
        }
Exemple #14
0
 public void WriteTo(TextWriter writer, HtmlEncoder encoder)
 {
     encoder.Encode(writer, fUnencoded);
 }
Exemple #15
0
 private static void RegistrationAccessServices(this IServiceCollection services)
 {
     services.AddScoped <ILoginService, LoginService>();
     services.AddScoped <IAccessTokenService, AccessTokenService>();
     services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Arabic));
 }
Exemple #16
0
 /// <summary>
 /// Writes the content by encoding it with the specified encoder to the specified
 /// writer.
 /// </summary>
 /// <param name="writer">The <see cref="TextWriter"/> to which the content is written.</param>
 /// <param name="encoder">The <see cref="HtmlEncoder"/> which encodes the content to be written.</param>
 public void WriteTo(TextWriter writer, HtmlEncoder encoder)
 {
     this.Html.WriteTo(writer, encoder);
 }
Exemple #17
0
 public VisitorsController(HtmlEncoder htmlEncoder, VisitorsDbContext dbContext = null)
 {
     _dbContext   = dbContext;
     _htmlEncoder = htmlEncoder;
 }
Exemple #18
0
 public void WriteTo(TextWriter writer, HtmlEncoder encoder)
 {
     writer.WriteLine(ToHtmlString());
 }
        public async Task GetChildContentAsync_CallsGetChildContentAsyncWithCacheAndEncoder(bool useCachedResult, HtmlEncoder encoder)
        {
            // Arrange
            bool?       passedUseCacheResult = null;
            HtmlEncoder passedEncoder        = null;
            var         content = new DefaultTagHelperContent();
            var         output  = new TagHelperOutput(
                tagName: "tag",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResultArgument, encoderArgument) =>
            {
                passedUseCacheResult = useCachedResultArgument;
                passedEncoder        = encoderArgument;
                return(Task.FromResult <TagHelperContent>(content));
            });

            // Act
            var result = await output.GetChildContentAsync(useCachedResult, encoder);

            // Assert
            Assert.True(passedUseCacheResult.HasValue);
            Assert.Equal(useCachedResult, passedUseCacheResult.Value);
            Assert.Same(encoder, passedEncoder);
            Assert.Same(content, result);
        }
        public static async Task RenderFortunesHtml(IEnumerable <Fortune> model, HttpContext httpContext, HtmlEncoder htmlEncoder)
        {
            httpContext.Response.StatusCode  = StatusCodes.Status200OK;
            httpContext.Response.ContentType = "text/html; charset=UTF-8";

            var sb = new StringBuilder();

            sb.Append("<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>");
            foreach (var item in model)
            {
                sb.Append("<tr><td>");
                sb.Append(item.Id.ToString(CultureInfo.InvariantCulture));
                sb.Append("</td><td>");
                sb.Append(htmlEncoder.Encode(item.Message));
                sb.Append("</td></tr>");
            }

            sb.Append("</table></body></html>");
            var response = sb.ToString();

            // fortunes includes multibyte characters so response.Length is incorrect
            httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(response);
            await httpContext.Response.WriteAsync(response);
        }
Exemple #21
0
 public InlineStyleTagHelper(IHostingEnvironment hostingEnvironment, IMemoryCache cache, HtmlEncoder htmlEncoder, JavaScriptEncoder javaScriptEncoder, IUrlHelperFactory urlHelperFactory)
     : base(hostingEnvironment, cache, htmlEncoder, javaScriptEncoder, urlHelperFactory)
 {
 }
Exemple #22
0
 public IHtmlContent RenderTitleSegments(string segment, string position = "0")
 {
     return(RenderTitleSegments(new HtmlString(HtmlEncoder.Encode(segment)), position));
 }
Exemple #23
0
 public PieController(IPieRepository pieRepository, ICategoryRepository categoryRepository, IPieReviewRepository pieReviewRepository, HtmlEncoder htmlEncoder)
 {
     _pieRepository       = pieRepository;
     _categoryRepository  = categoryRepository;
     _pieReviewRepository = pieReviewRepository;
     _htmlEncoder         = htmlEncoder;
 }
Exemple #24
0
 public Task <TagHelperContent> GetChildContentAsync(HtmlEncoder encoder)
 {
     throw null;
 }
Exemple #25
0
 public AbpPaginationTagHelperService(IHtmlGenerator generator, HtmlEncoder encoder, IStringLocalizer <AbpUiResource> localizer)
 {
     _generator = generator;
     _encoder   = encoder;
     _localizer = localizer;
 }
Exemple #26
0
        public void WriteTo(TextWriter writer, HtmlEncoder encoder)
        {
            var htmlString = GenerateHtmlString();

            writer.Write(htmlString);
        }
Exemple #27
0
 public Task <TagHelperContent> GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
 {
     throw null;
 }
 public AbpSelectTagHelperService(IHtmlGenerator generator, HtmlEncoder encoder, IAbpTagHelperLocalizer tagHelperLocalizer)
 {
     _generator          = generator;
     _encoder            = encoder;
     _tagHelperLocalizer = tagHelperLocalizer;
 }
Exemple #29
0
 /// <summary>
 /// Gets the content.
 /// </summary>
 /// <param name="encoder">The <see cref="HtmlEncoder"/>.</param>
 /// <returns>A <see cref="string"/> containing the content.</returns>
 public abstract string GetContent(HtmlEncoder encoder);
Exemple #30
0
 public void StartTagHelperWritingScope(HtmlEncoder encoder)
 {
 }
Exemple #31
0
 /// <inheritdoc />
 public abstract void WriteTo(TextWriter writer, HtmlEncoder encoder);
Exemple #32
0
 static Encoders()
 {
     HtmlEncode = DefaultHtmlEncode;
 }
Exemple #33
0
 public void WriteTo(TextWriter writer, HtmlEncoder encoder)
 {
     RenderPartialViewToString(writer, GridViewName, _source, _viewContext, _viewEngine);
 }
Exemple #34
0
        public void HtmlEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All); // allow all codepoints

            // "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
            const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
            const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD&#x103FF;e\uFFFD";

            // Act
            string retVal = encoder.HtmlEncode(input);

            // Assert
            Assert.Equal(expected, retVal);
        }
 public ProcessFormPostResponse(HtmlEncoder encoder)
 => _encoder = encoder;
Exemple #36
0
        public void HtmlEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder();
            string input = "Hello, there!";

            // Act & assert
            Assert.Same(input, encoder.HtmlEncode(input));
        }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
            }
                ).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("192.168.1.43"));
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });


            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddAntiforgery();

            services.AddMvc(options =>
            {
                //var policy = new AuthorizationPolicyBuilder()
                //         .RequireAuthenticatedUser()
                //         .Build();
                //options.Filters.Add(new AuthorizeFilter(policy));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("xml", MediaTypeHeaderValue.Parse("application/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("config", MediaTypeHeaderValue.Parse("application/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("js", MediaTypeHeaderValue.Parse("application/json"));
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                options.ModelBinderProviders.Add(new ArrayModelBinderProvider());
                options.ModelBinderProviders.Add(new CollectionModelBinderProvider());

                options.ValueProviderFactories.Add(new JQueryQueryStringValueProviderFactory());
                //options.ValueProviderFactories.Add(new CookieValueProviderFactory());
                options.ModelMetadataDetailsProviders.Add(
                    new ExcludeBindingMetadataProvider(typeof(System.Version)));
                options.ModelMetadataDetailsProviders.Add(
                    new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
                //options.Conventions.Add(new RouteTokenTransformerConvention(
                //    new SlugifyParameterTransformer()));
            })
            .AddXmlDataContractSerializerFormatters()
            .AddXmlSerializerFormatters()
            .AddDataAnnotationsLocalization(options =>
            {
                //options.DataAnnotationLocalizerProvider = (type, factory) =>
                //    factory.Create(typeof(SharedResource));
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);


            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr")
                };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
                options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
                {
                    // My custom request culture logic
                    return(new ProviderCultureResult("en"));
                }));
            });
            services.AddResponseCaching();
            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromDays(30);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            services.AddRouting(options =>

                                options.LowercaseUrls = true
                                );
            services.AddDistributedMemoryCache(options =>
            {
            });

            services.AddDistributedSqlServerCache(options =>
            {
                options.ConnectionString = "Server=localhost; Database=IntuitDb;User Id=US;Password=Bg-15rzbb; Trusted_Connection=True;";
                options.SchemaName       = "dbo";
                options.TableName        = "TestCache";
            });
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
            });

            services.Configure <CookieTempDataProviderOptions>(options =>
            {
                options.Cookie.IsEssential = true;
            });

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost";
                options.InstanceName  = "SampleInstance";
            });

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <BrotliCompressionProvider>();
                options.Providers.Add <GzipCompressionProvider>();
                //options.Providers.Add<CustomCompressionProvider>();
                options.MimeTypes =
                    ResponseCompressionDefaults.MimeTypes.Concat(
                        new[] { "image/svg+xml" });
            });
            //AuthConfigurer.Configure(services, Configuration);
            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                                          UnicodeRanges.CjkUnifiedIdeographs }));
            services.Configure <BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure <IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
                options.ForwardClientCertificate = false;
            });
            services.Configure <IISServerOptions>(options =>
            {
                options.AutomaticAuthentication = false;
            });
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");


            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "Intuit API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <IntuitWebHostModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig("log4net.config")
                           )
                       ));
        }
Exemple #38
0
        public void HtmlEncode_StringSubstring()
        {
            // Arrange
            HtmlEncoder encoder = new HtmlEncoder();
            var output = new StringWriter();

            // Act
            encoder.HtmlEncode("Hello+world!", 3, 5, output);

            // Assert
            Assert.Equal("lo&#x2B;wo", output.ToString());
        }
Exemple #39
0
        public void ConfigureServices(IServiceCollection services)
        {
            //自定注册
            AddAssembly(services, "FytSoa.Service");

            //解决视图输出内容中文编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/fytadmin/login");
            })
            //新增一个新的方案
            .AddCookie(CompanyAuthorizeAttribute.CompanyAuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/company/login");
            })
            .AddJwtBearer(JwtAuthorizeAttribute.JwtAuthenticationScheme, o =>
            {
                var jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,                                                                               //是否验证Issuer
                    ValidateAudience         = true,                                                                               //是否验证Audience
                    ValidateIssuerSigningKey = true,                                                                               //是否验证SecurityKey
                    ValidateLifetime         = true,                                                                               //是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew
                    ClockSkew             = TimeSpan.FromSeconds(30),                                                              //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ValidAudience         = jwtConfig.Audience,                                                                    //Audience
                    ValidIssuer           = jwtConfig.Issuer,                                                                      //Issuer,这两项和前面签发jwt的设置一致
                    RequireExpirationTime = true,
                    IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtAuth:SecurityKey"])) //拿到SecurityKey
                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("App", policy => policy.RequireRole("App").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            #endregion

            #region 缓存配置
            services.AddMemoryCache();
            services.AddSingleton <ICacheService, MemoryCacheService>();
            RedisHelper.Initialization(new CSRedis.CSRedisClient(Configuration["Cache:Configuration"]));
            #endregion

            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/web/index", "/");
            });

            #region Swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "FytSoa API",
                    Contact = new Contact {
                        Name = "feiyit", Email = "*****@*****.**", Url = "http://www.feiyit.com"
                    }
                });
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath       = Path.Combine(basePath, "FytSoa.Web.xml");
                var entityXmlPath = Path.Combine(basePath, "FytSoa.Core.xml");
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(entityXmlPath);
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    //jwt默认的参数名称
                    Name = "Authorization",
                    //jwt默认存放Authorization信息的位置(请求头中)
                    In   = "header",
                    Type = "apiKey"
                });
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:4909")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion

            #region 性能 压缩
            services.AddResponseCompression();
            #endregion

            //NLog 数据库配置
            //NLog.LogManager.Configuration.FindTargetByName<NLog.Targets.DatabaseTarget>("db").ConnectionString = Configuration.GetConnectionString("LogConnectionString");
        }
Exemple #40
0
        private void GenerateSignalEvents(GeneratorOutput generatorOutput)
        {
            foreach (var block in from output in generatorOutput.Outputs
                     from block in output.FindBlocks(BlockKind.Event)
                     select block)
            {
                Event @event = (Event)block.Object;
                if (this.events.Contains(@event))
                {
                    block.Text.StringBuilder.Clear();
                    Class @class = (Class)@event.Namespace;

                    int           argNum          = 1;
                    StringBuilder fullNameBuilder = new StringBuilder("global::System.Action");
                    foreach (Parameter parameter in @event.Parameters)
                    {
                        argNum++;
                        if (argNum == 2)
                        {
                            fullNameBuilder.Append('<');
                        }
                        fullNameBuilder.Append(parameter.Type);
                        fullNameBuilder.Append(',');
                    }
                    if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                    {
                        fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                    }
                    string signature = string.Format("{0}({1})", @event.OriginalName,
                                                     string.Join(", ",
                                                                 from e in @event.Parameters
                                                                 select GetOriginalParameterType(e)));
                    Event existing = @class.Events.FirstOrDefault(e => e.Name == @event.Name);
                    if (existing != null && existing != @event)
                    {
                        if (@event.Parameters.Count > 0)
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                        else
                        {
                            existing.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    else
                    {
                        if (@event.Parameters.Count > 0 &&
                            (@class.Methods.Any(m => m.IsGenerated && m.OriginalName == @event.Name) ||
                             @class.Properties.Any(p => p.IsGenerated && p.OriginalName == @event.Name)))
                        {
                            @event.Name += GetSignalEventSuffix(@event);
                        }
                    }
                    if (@event.OriginalDeclaration.Comment != null)
                    {
                        block.WriteLine("/// <summary>");
                        foreach (string line in HtmlEncoder.HtmlEncode(@event.OriginalDeclaration.Comment.BriefText).Split(
                                     Environment.NewLine.ToCharArray()))
                        {
                            block.WriteLine("/// <para>{0}</para>", line);
                        }
                        block.WriteLine("/// </summary>");
                    }
                    var finalName = char.ToUpperInvariant(@event.Name[0]) + @event.Name.Substring(1);
                    if (@event.Namespace.Declarations.Exists(d => d != @event && d.Name == finalName))
                    {
                        finalName += "Signal";
                    }
                    block.WriteLine(string.Format(@"public event {0} {1}
{{
	add
	{{
        ConnectDynamicSlot(this, ""{2}"", value);
	}}
	remove
	{{
        DisconnectDynamicSlot(this, ""{2}"", value);
	}}
}}", fullNameBuilder, finalName, signature));
                }
            }
            var qtMetacall = (from output in generatorOutput.Outputs
                              from block in output.FindBlocks(BlockKind.Method)
                              let declaration = block.Object as Declaration
                                                where declaration != null && declaration.Name == "QtMetacall" &&
                                                declaration.Namespace.Name == "QObject"
                                                select block).FirstOrDefault();

            if (qtMetacall != null)
            {
                qtMetacall.Text.StringBuilder.Replace("return __ret;", "return HandleQtMetacall(__ret, _0, _2);");
            }
        }
Exemple #41
0
        public void ConfigureServices(IServiceCollection services)
        {
            #region 注册服务
            services.AddTransient <ICmsSiteService, CmsSiteService>();
            services.AddTransient <ICmsImgTypeService, CmsImgTypeService>();
            services.AddTransient <ICmsImageService, CmsImageService>();
            services.AddTransient <ICmsColumnService, CmsColumnService>();
            services.AddTransient <ICmsTemplateService, CmsTemplateService>();
            services.AddTransient <ICmsArticleService, CmsArticleService>();
            services.AddTransient <ICmsAdvClassService, CmsAdvClassService>();
            services.AddTransient <ICmsAdvListService, CmsAdvListService>();
            services.AddTransient <ICmsMessageService, CmsMessageService>();
            services.AddTransient <ICmsDownloadService, CmsDownloadService>();

            services.AddTransient <ISysAppSettingService, SysAppSettingService>();
            services.AddTransient <ISysAuthorizeService, SysAuthorizeService>();
            services.AddTransient <ISysBtnFunService, SysBtnFunService>();
            services.AddTransient <ISysPermissionsService, SysPermissionsService>();
            services.AddTransient <ISysLogService, SysLogService>();
            services.AddTransient <ISysAdminService, SysAdminService>();
            services.AddTransient <ISysCodeService, SysCodeService>();
            services.AddTransient <ISysCodeTypeService, SysCodeTypeService>();
            services.AddTransient <ISysOrganizeService, SysOrganizeService>();
            services.AddTransient <ISysMenuService, SysMenuService>();
            services.AddTransient <ISysRoleService, SysRoleService>();
            #endregion

            //解决视图输出内容中文编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //services.AddAuthentication(options =>
            //{
            //    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            //    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            //})
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/fytadmin/login");
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = "FytSos",
                    ValidAudience    = "wr",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = true,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireApp", policy => policy.RequireRole("App").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            #endregion

            #region 缓存 读取配置是否使用哪种缓存模式
            services.AddMemoryCache();
            if (Convert.ToBoolean(Configuration["Cache:IsUseRedis"]))
            {
                services.AddSingleton <ICacheService, RedisCacheService>();
            }
            else
            {
                services.AddSingleton <ICacheService, MemoryCacheService>();
            }
            #endregion

            #region 缓存 RedisCache
            //将Redis分布式缓存服务添加到服务中
            services.AddDistributedRedisCache(options =>
            {
                //用于连接Redis的配置
                options.Configuration = "localhost";// Configuration.GetConnectionString("RedisConnectionString");
                //Redis实例名RedisDistributedCache
                options.InstanceName = "RedisInstance";
            });
            #endregion

            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/web/index", "/");
            });

            #region Swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "FytSoa API",
                    Contact = new Contact {
                        Name = "feiyit", Email = "*****@*****.**", Url = "http://www.feiyit.com"
                    }
                });
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath       = Path.Combine(basePath, "FytSoa.Web.xml");
                var entityXmlPath = Path.Combine(basePath, "FytSoa.Core.xml");
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(entityXmlPath);
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    //jwt默认的参数名称
                    Name = "Authorization",
                    //jwt默认存放Authorization信息的位置(请求头中)
                    In   = "header",
                    Type = "apiKey"
                });
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:4909")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion

            #region 性能 压缩
            services.AddResponseCompression();
            #endregion
        }
Exemple #42
0
 public void TestEntityWithSemicolon()
 {
     var encoder = new HtmlEncoder();
     Assert.AreEqual(">", encoder.Decode("&gt;"));
 }
 public TextBoxTagHelper(IHtmlHelper htmlHelper, HtmlEncoder htmlEncoder)
 {
     _htmlHelper  = htmlHelper as HtmlHelper;
     _htmlEncoder = htmlEncoder;
 }
Exemple #44
0
        public void UrlEncode_DoesNotOutputHtmlSensitiveCharacters()
        {
            // Per the design document, we provide additional defense-in-depth
            // by never emitting HTML-sensitive characters unescaped.

            // Arrange
            UrlEncoder urlEncoder = new UrlEncoder(UnicodeRanges.All);
            HtmlEncoder htmlEncoder = new HtmlEncoder(UnicodeRanges.All);

            // Act & assert
            for (int i = 0; i <= 0x10FFFF; i++)
            {
                if (IsSurrogateCodePoint(i))
                {
                    continue; // surrogates don't matter here
                }

                string urlEncoded = urlEncoder.UrlEncode(Char.ConvertFromUtf32(i));
                string thenHtmlEncoded = htmlEncoder.HtmlEncode(urlEncoded);
                Assert.Equal(urlEncoded, thenHtmlEncoded); // should have contained no HTML-sensitive characters
            }
        }
Exemple #45
0
 public SessionModel(IApiClient apiClient, HtmlEncoder htmlEncoder)
 {
     _apiClient   = apiClient;
     _htmlEncoder = htmlEncoder;
 }