2016-03-09 19 views
1

我需要過濾我的項目中的所有字符串以防止XSS攻擊。 我決定通過使用全局模型聯編程序來完成。 下面可以看到模型粘合劑註冊碼:vNext模型過濾器字符串的活頁夾

public IServiceProvider ConfigureServices(IServiceCollection services) 
{ 
    services.AddMvc().AddMvcOptions(options => 
    { 
     options.ModelBinders.Add(new AntiXSSModelBinder()); 
    }); 
} 

要求就是過濾既簡單參數字符串和字符串內複雜類型(任何嵌套級):

public async Task<IActionResult> GetShippingAddress(string id) 
public async Task<IActionResult> AddUpdateShippingMethod(AddUpdateShippingMethodModel model) 
// AddUpdateShippingMethodModel has Text property of string type 

濾波方法的實施例:

public class AntiXSSModelBinder : IModelBinder 
{ 
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) 
    { 
     // ... 
    } 

    private string FilterPotentiallyXSSEntries(string value) 
    { 
     return value.Replace("<", "").Replace(">", "").Replace("script", ""); 
    } 
} 

在ModelBinder主題上沒有很好的文檔,所以任何幫助將不勝感激。

+0

我覺得你在做這個倒退。一般的最佳做法是在輸出點進行編碼,無論是視圖,XML序列化器,JSON序列化器或其他。相反,您將數據鎖定在HTML中,根據數據結束的位置,過濾器效果不佳,而更糟糕的是,使用剃鬚刀時,如果您決定編碼到實體而不是替換爲空間。 – blowdart

回答

0
public class AntiXSSModelBinder : IModelBinder 
{ 
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelMetadata.IsComplexType) 
     { 
      // this type cannot be converted 
      return ModelBindingResult.NoResultAsync; 
     } 

     var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     if (valueProviderResult == ValueProviderResult.None) 
     { 
      // no entry 
      return ModelBindingResult.NoResultAsync; 
     } 

     var model = valueProviderResult.ConvertTo(bindingContext.ModelType); 

     if (bindingContext.ModelType == typeof(string)) 
     { 
      var modelAsString = model as string; 

      if (model != null) 
      { 
       return ModelBindingResult.SuccessAsync(bindingContext.ModelName, FilterPotentiallyXSSEntries(modelAsString)); 
      } 
     } 

     return ModelBindingResult.NoResultAsync; 
    } 

    private static string FilterPotentiallyXSSEntries(string value) 
    { 
     return value.Replace("<", "").Replace(">", "").Replace("script", ""); 
    } 
} 

適用於各級嵌套。