net mvc webapi 实用

时间:2023-03-09 04:10:22
net mvc webapi 实用

asp.net mvc webapi 实用的接口加密方法

在很多项目中,因为webapi是对外开放的,这个时候,我们就要得考虑接口交换数据的安全性。

安全机制也比较多,如andriod与webapi 交换数据的时候,可以走双向证书方法,但是开发成本比较大,

今天我们不打算介绍这方面的知识,我们说说一个较简单也较常见的安全交换机制

在这里要提醒读者,目前所有的加密机制都不是绝对的安全!

我们的目标是,任何用户或者软件获取到我们的webapi接口url后用来再次访问该地址都是无效的!

达到这种目标的话,我们必须要在url中增加一个时间戳,但是仅仅如此还是不够,用户可以修改我们的时间戳!

因此我们可以对时间戳 进行MD5加密,但是这样依然不够,用户可以直接对我们的时间戳md5的哦,因些需要引入一个绝对安全

双方约定的key,并同时加入其它参数进行混淆!

注意:这个key要在app里和我们的webapi里各保存相同的一份!

于是我们约定公式: 加密结果=md5(时间戳+随机数+key+post或者get的参数)

下面我们开始通过上述公式写代码:

于由我的环境是asp.net mvc 的,所以重写一个加密类ApiSecurityFilter

1、获取参数

net mvc webapi 实用
if (request.Headers.Contains("timestamp"))
timestamp = HttpUtility.UrlDecode(request.Headers.GetValues("timestamp").FirstOrDefault()); if (request.Headers.Contains("nonce"))
nonce = HttpUtility.UrlDecode(request.Headers.GetValues("nonce").FirstOrDefault()); if (request.Headers.Contains("signature"))
signature = HttpUtility.UrlDecode(request.Headers.GetValues("signature").FirstOrDefault()); if (string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature))
throw new SecurityException();
net mvc webapi 实用

2、判断时间戳是否超过指定时间

net mvc webapi 实用
   double ts = 0;
bool timespanvalidate = double.TryParse(timestamp, out ts); bool falg = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds - ts > 60 * 1000; if (falg || (!timespanvalidate))
throw new SecurityException();
net mvc webapi 实用

3、POST/DELETE/UPDATE 三种方式提取参数

net mvc webapi 实用
  case "POST":
case "PUT":
case "DELETE": Stream stream = HttpContext.Current.Request.InputStream;
StreamReader streamReader = new StreamReader(stream);
sortedParams = new SortedDictionary<string, string>(new JsonSerializer().Deserialize<Dictionary<string, string>>(new JsonTextReader(streamReader))); break;
net mvc webapi 实用

4、GET 方式提取参数

net mvc webapi 实用
case "GET":

                    IDictionary<string, string> parameters = new Dictionary<string, string>();

                    foreach (string key in HttpContext.Current.Request.QueryString)
{
if (!string.IsNullOrEmpty(key))
{
parameters.Add(key, HttpContext.Current.Request.QueryString[key]);
}
} sortedParams = new SortedDictionary<string, string>(parameters); break;
net mvc webapi 实用

5、排序上述参数并拼接,形成我们要参与md5的约定公式中的第四个参数

net mvc webapi 实用
            StringBuilder query = new StringBuilder();

            if (sortedParams != null)
{
foreach (var sort in sortedParams.OrderBy(k => k.Key))
{
if (!string.IsNullOrEmpty(sort.Key))
{
query.Append(sort.Key).Append(sort.Value);
}
} data = query.ToString().Replace(" ", "");
}
net mvc webapi 实用

6、开始约定公式计算结果并对比传过的结果是否一致

   var md5Staff = Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp + nonce + staffId + data), 32);

            if (!md5Staff.Equals(signature))
throw new SecurityException();

完整的代码如下:

net mvc webapi 实用
 1 public class ApiSecurityFilter : ActionFilterAttribute
2 {
3 public override void OnActionExecuting(HttpActionContext actionContext)
4 {
5 var request = actionContext.Request;
6
7 var method = request.Method.Method;
8 var staffId = "^***********************************$";
9
10 string timestamp = string.Empty, nonce = string.Empty, signature = string.Empty;
11
12 if (request.Headers.Contains("timestamp"))
13 timestamp = request.Headers.GetValues("timestamp").FirstOrDefault();
14
15 if (request.Headers.Contains("nonce"))
16 nonce = request.Headers.GetValues("nonce").FirstOrDefault();
17
18 if (request.Headers.Contains("signature"))
19 signature = request.Headers.GetValues("signature").FirstOrDefault();
20
21 if (string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature))
22 throw new SecurityException();
23
24 double ts = 0;