开发工具:Visual Studio 2017

C#版本:C#7.1

最有效的防止SQL注入的方式是调用数据库时使用参数化查询。

但是如果是接手一个旧的WebApi项目,不想改繁多的数据库访问层的代码,应该如何做。

我的解决方案是加一个过滤器。

先写过滤方法,上代码

using System;
using System.Collections.Generic;
using System.Web; namespace Test
{
/// <summary>
/// 防止SQL注入
/// </summary>
public class AntiSqlInject
{
public static AntiSqlInject Instance = new AntiSqlInject(); /// <summary>
/// 初始化过滤方法
/// </summary>
static AntiSqlInject()
{
SqlKeywordsArray.AddRange(SqlSeparatKeywords.Split('|'));
SqlKeywordsArray.AddRange(Array.ConvertAll(SqlCommandKeywords.Split('|'), h => h + " "));
SqlKeywordsArray.AddRange(Array.ConvertAll(SqlCommandKeywords.Split('|'), h => " " + h));
} private const string SqlCommandKeywords = "and|exec|execute|insert|select|delete|update|count|chr|mid|master|" +
"char|declare|sitename|net user|xp_cmdshell|or|create|drop|table|from|grant|use|group_concat|column_name|" +
"information_schema.columns|table_schema|union|where|select|delete|update|orderhaving|having|by|count|*|truncate|like"; private const string SqlSeparatKeywords = "'|;|--|\'|\"|/*|%|#"; private static readonly List<string> SqlKeywordsArray = new List<string>(); /// <summary>
/// 是否安全
/// </summary>
/// <param name="input">输入</param>
/// <returns>返回</returns>
public bool IsSafetySql(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return true;
}
input = HttpUtility.UrlDecode(input).ToLower(); foreach (var sqlKeyword in SqlKeywordsArray)
{
if (input.IndexOf(sqlKeyword, StringComparison.Ordinal) >= 0)
{
return false;
}
}
return true;
} /// <summary>
/// 返回安全字符串
/// </summary>
/// <param name="input">输入</param>
/// <returns>返回</returns>
public string GetSafetySql(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
if (IsSafetySql(input)) { return input; }
input = HttpUtility.UrlDecode(input).ToLower(); foreach (var sqlKeyword in SqlKeywordsArray)
{
if (input.IndexOf(sqlKeyword, StringComparison.Ordinal) >= 0)
{
input = input.Replace(sqlKeyword, string.Empty);
}
}
return input;
}
}
}

然后是过滤器,先上代码

using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace Test
{
/// <inheritdoc>
/// <cref></cref>
/// </inheritdoc>
/// <summary>
/// SQL注入过滤器
/// </summary>
public class AntiSqlInjectFilter : ActionFilterAttribute
{
/// <inheritdoc />
/// <summary>
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(HttpActionContext filterContext)
{
base.OnActionExecuting(filterContext);
var actionParameters = filterContext.ActionDescriptor.GetParameters(); var actionArguments = filterContext.ActionArguments; foreach (var p in actionParameters)
{
var value = filterContext.ActionArguments[p.ParameterName]; var pType = p.ParameterType; if (value == null)
{
continue;
}
//如果不是值类型或接口,不需要过滤
if (!pType.IsClass) continue; if (value is string)
{
//对string类型过滤
filterContext.ActionArguments[p.ParameterName] = AntiSqlInject.Instance.GetSafetySql(value.ToString());
}
else
{
//是一个class,对class的属性中,string类型的属性进行过滤
var properties = pType.GetProperties();
foreach (var pp in properties)
{
var temp = pp.GetValue(value);
if (temp == null)
{
continue;
}
pp.SetValue(value, temp is string ? AntiSqlInject.Instance.GetSafetySql(temp.ToString()) : temp);
}
}
} }
}
}

思路是,加过滤器继承ActionFilterAttribute,重写OnActionExecuting方法,获取入参,对入参中的string类型的所有数据进行过滤。两种情况,一是参数是string类型,二是类的属性。过滤器搞定。

过滤器有两种使用方式,一种是在具体的方法上添加

		[HttpPut,Route("api/editSomething")]
[AntiSqlInjectFilter]
public async Task<bool> EditSomeThingAsync([FromBody]SomeThingmodel)
{
var response = await SomeThingBusiness.Editsync(model);
return response;
}

一种是全局配置,在WebApiConfig.cs文件中的Register方法中加上过滤器

using System.Web.Http;

namespace Test
{
/// <summary>
/// WebApi配置
/// </summary>
public static class WebApiConfig
{
/// <summary>
/// 注册配置服务
/// </summary>
/// <param name="config"></param>
public static void Register(HttpConfiguration config)
{
// Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//全局配置防止SQL注入过滤
config.Filters.Add(new AntiSqlInjectFilter());
}
}
}

测试有效。

适用于WebApi的SQL注入过滤器的更多相关文章

  1. 结合jquery的前后端加密解密 适用于WebApi的SQL注入过滤器 Web.config中customErrors异常信息配置 ife2018 零基础学院 day 4 ife2018 零基础学院 day 3 ife 零基础学院 day 2 ife 零基础学院 day 1 - 我为什么想学前端

    在一个正常的项目中,登录注册的密码是密文传输到后台服务端的,也就是说,首先前端js对密码做处理,随后再传递到服务端,服务端解密再加密传出到数据库里面.Dotnet已经提供了RSA算法的加解密类库,我们 ...

  2. Java 防SQL注入过滤器(拦截器)代码

    原文出自:https://blog.csdn.net/seesun2012 前言 浅谈SQL注入:        所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符 ...

  3. SQL盲注、SQL注入 - SpringBoot配置SQL注入过滤器

    1. SQL盲注.SQL注入   风险:可能会查看.修改或删除数据库条目和表.   原因:未对用户输入正确执行危险字符清理.   固定值:查看危险字符注入的可能解决方案. 2. pom.xml添加依赖 ...

  4. SQL注入的优化和绕过

    作者:Arizona 原文来自:https://bbs.ichunqiu.com/thread-43169-1-1.html 0×00 ~ 介绍 SQL注入毫无疑问是最危险的Web漏洞之一,因为我们将 ...

  5. 170605、防止sql注入(二)

    java filter防止sql注入攻击 原理,过滤所有请求中含有非法的字符,例如:, & <  select delete 等关键字,黑客可以利用这些字符进行注入攻击,原理是后台实现使 ...

  6. Java防止SQL注入2(通过filter过滤器功能进行拦截)

    首先说明一点,这个过滤器拦截其实是不靠谱的,比如说我的一篇文章是介绍sql注入的,或者评论的内容是有关sql的,那会过滤掉:且如果每个页面都经过这个过滤器,那么效率也是非常低的. 如果是要SQL注入拦 ...

  7. 使用过滤器解决SQL注入和跨站点脚本编制

    1 SQL注入.盲注 1.1 SQL注入.盲注概述 Web 应用程序通常在后端使用数据库,以与企业数据仓库交互.查询数据库事实上的标准语言是 SQL(各大数据库供应商都有自己的不同版本).Web 应用 ...

  8. XSS过滤JAVA过滤器filter 防止常见SQL注入

    Java项目中XSS过滤器的使用方法. 简单介绍: XSS : 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩 ...

  9. JSP使用过滤器防止SQL注入

    什么是SQL注入攻击?引用百度百科的解释: sql注入_百度百科: 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.具 ...

随机推荐

  1. Excel VBA(宏):添加宏

    写在前面: .编写宏,打开VBA,双击ThisWorkbook对当前工作薄进行编写宏:双击Sheet1,对整个sheet编写宏: 或者创建模块,在模块里,编写.调试代码. 打开VBA的方法见第一讲,结 ...

  2. ios uibutton加数字角标

    http://www.jianshu.com/p/0c7fae1cadac 第一种:https://github.com/mikeMTOL/UIBarButtonItem-Badge第二种:https ...

  3. 设置MessageBox自动关闭

    通过设置定时器,让定时器的Tick事件模拟往MessageBox发送一个Enter按钮代替用鼠标点击MessageBox上的确定按钮,来实现MessageBox的自动关闭,实现代码如下: System ...

  4. #227 Generate Random Whole Numbers within a Range

    我们之前生成的随机数是在0到某个数之间,现在我们要生成的随机数是在两个指定的数之间. 我们需要定义一个最小值和一个最大值. 下面是我们将要使用的方法,仔细看看并尝试理解这行代码到底在干嘛: Math. ...

  5. 《JavaScript 高级程序设计》读书笔记一 简介

    一   历史 二   实现 a. javascript三个部分: ECMAScript:由ECMA-262定义,提供核心语言功能: DOM:提供HTML的应用程序编程接口/提供访问和操作网页内容的方法 ...

  6. gitlab导入现在git项目

    确保管理员所在机器的ssh 公钥已经保存在gitlab网站上. 这样管理员可以在自己的机器上和gitlab系统交互. 现在在管理员自己的机器上,进入项目目录(项目目录拷贝自git server,目录后 ...

  7. DVWA 1.9 通关秘籍

    DVWA 1.9 通关秘籍   本文来源:i春秋社区-分享你的技术,为安全加点温度    DVWA (Dam Vulnerable Web Application) DVWA是用PHP+Mysql编写 ...

  8. Javascript高级编程学习笔记(29)—— BOM(3)location对象

    在JS中location是一个神奇的对象 它既是window对象的属性,也是document对象的属性 它的作用主要在于保存当前文档页面的信息,以及将 url 解析为独立的片段 location对象属 ...

  9. [部署]CentOS安装PHP环境

    环境 虚拟机:VMWare10.0.1 build-1379776 操作系统:CentOS7 64位 HTTP Server:Apache(httpd) 步骤 PHP环境需要HTTP服务器支持,本文使 ...

  10. Mac OS Eclipse 调试快捷键不好使(失效)的情况

    Eclipse调试使用的F5  F6  F8一直都好用,结果一次调试后忽然不好使. 问题原因,尚未知晓. 解决办法,重启机器.