在不少項目中,由於webapi是對外開放的,這個時候,咱們就要得考慮接口交換數據的安全性。html
安全機制也比較多,如andriod與webapi 交換數據的時候,能夠走雙向證書方法,可是開發成本比較大,ios
今天咱們不打算介紹這方面的知識,咱們說說一個較簡單也較常見的安全交換機制web
在這裏要提醒讀者,目前全部的加密機制都不是絕對的安全!json
咱們的目標是,任何用戶或者軟件獲取到咱們的webapi接口url後用來再次訪問該地址都是無效的!小程序
達到這種目標的話,咱們必需要在url中增長一個時間戳,可是僅僅如此仍是不夠,用戶能夠修改咱們的時間戳!微信小程序
所以咱們能夠對時間戳 進行MD5加密,可是這樣依然不夠,用戶能夠直接對咱們的時間戳md5的哦,因些須要引入一個絕對安全api
的雙方約定的key,並同時加入其它參數進行混淆!安全
注意:這個key要在app裏和咱們的webapi裏各保存相同的一份!微信
因而咱們約定公式: 加密結果=md5(時間戳+隨機數+key+post或者get的參數)mvc
下面咱們開始經過上述公式寫代碼:
於由個人環境是asp.net mvc 的,因此重寫一個加密類ApiSecurityFilter
一、獲取參數
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();
二、判斷時間戳是否超過指定時間
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();
三、POST/DELETE/UPDATE 三種方式提取參數
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;
四、GET 方式提取參數
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;
五、排序上述參數並拼接,造成咱們要參與md5的約定公式中的第四個參數
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(" ", ""); }
六、開始約定公式計算結果並對比傳過的結果是否一致
var md5Staff = Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp + nonce + staffId + data), 32); if (!md5Staff.Equals(signature)) throw new SecurityException();
完整的代碼以下:
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; 25 bool timespanvalidate = double.TryParse(timestamp, out ts); 26 27 bool falg = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds - ts > 60 * 1000; 28 29 if (falg || (!timespanvalidate)) 30 throw new SecurityException("timeSpanValidate"); 31 32 var data = string.Empty; 33 IDictionary<string, string> sortedParams = null; 34 35 switch (method.ToUpper()) 36 { 37 case "POST": 38 case "PUT": 39 case "DELETE": 40 41 Stream stream = HttpContext.Current.Request.InputStream; 42 StreamReader streamReader = new StreamReader(stream); 43 sortedParams = new SortedDictionary<string, string>(new JsonSerializer().Deserialize<Dictionary<string, string>>(new JsonTextReader(streamReader))); 44 45 break; 46 47 case "GET": 48 49 IDictionary<string, string> parameters = new Dictionary<string, string>(); 50 51 foreach (string key in HttpContext.Current.Request.QueryString) 52 { 53 if (!string.IsNullOrEmpty(key)) 54 { 55 parameters.Add(key, HttpContext.Current.Request.QueryString[key]); 56 } 57 } 58 59 sortedParams = new SortedDictionary<string, string>(parameters); 60 61 break; 62 63 default: 64 throw new SecurityException("defaultOptions"); 65 } 66 67 StringBuilder query = new StringBuilder(); 68 69 if (sortedParams != null) 70 { 71 foreach (var sort in sortedParams.OrderBy(k => k.Key)) 72 { 73 if (!string.IsNullOrEmpty(sort.Key)) 74 { 75 query.Append(sort.Key).Append(sort.Value); 76 } 77 } 78 79 data = query.ToString().Replace(" ", ""); 80 } 81 82 var md5Staff = Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp + nonce + staffId + data), 32); 83 84 if (!md5Staff.Equals(signature)) 85 throw new SecurityException("md5Staff"); 86 87 base.OnActionExecuting(actionContext); 88 } 89 90 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 91 { 92 base.OnActionExecuted(actionExecutedContext); 93 } 94 }
七、最後在asp.net mvc 里加入配置上述類
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services config.Filters.Add(new ApiSecurityFilter()); config.Filters.Add(new ApiHandleErrorAttribute()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
八、添加寫入日誌類(此類不是本文重點,詳細參考 http://www.cnblogs.com/laogu2/p/5912153.html)
public class ApiHandleErrorAttribute: ExceptionFilterAttribute { /// <summary> /// add by laiyunba /// </summary> /// <param name="filterContext">context oop</param> public override void OnException(HttpActionExecutedContext filterContext) { LoggerFactory.CreateLog().LogError(Messages.error_unmanagederror, filterContext.Exception); } }
九、利用微信小程序測試接口
var data = { UserName: username, Password: password, Action: 'Mobile', Sms: '' }; var timestamp = util.gettimestamp(); var nonce = util.getnonce(); if (username && password) { wx.request({ url: rootUrl + '/api/login', method: "POST", data: data, header: { 'content-type': 'application/json', 'timestamp': timestamp, 'nonce': nonce, 'signature': util.getMD5Staff(data, timestamp, nonce) }, success: function (res) { if (res.data) {
1)其中getMD5Staff函數:
function getMD5Staff(queryData, timestamp, nonce) { var staffId = getstaffId();//保存的key與webapi同步 var data = dictionaryOrderWithData(queryData); return md5.md5(timestamp + nonce + staffId + data); }
2)dictionaryOrderWithData函數:
function dictionaryOrderWithData(dic) { //eg {x:2,y:3,z:1} var result = ""; var sdic = Object.keys(dic).sort(function (a, b) { return a.localeCompare(b) }); var value = ""; for (var ki in sdic) { if (dic[sdic[ki]] == null) { value = "" } else { value = dic[sdic[ki]]; } result += sdic[ki] + value; } return result.replace(/\s/g, ""); }
十、測試日誌
LaiyunbaApp Error: 2 : 2017-10-18 09:15:25 Unmanaged error in aplication, the exception information is Exception:System.Security.SecurityException: 安全性錯誤。 在 DistributedServices.MainBoundedContext.FilterAttribute.ApiSecurityFilter.OnActionExecuting(HttpActionContext actionContext) 在 System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) --- 引起異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext() --- 引起異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- 引起異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext() 失敗的程序集的區域是: MyComputer LogicalOperationStack=2017-10-18 09:15:25 2017-10-18 09:15:25 DateTime=2017-10-18T01:15:25.1000017Z 2017-10-18 09:15:25 Callstack= 在 System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) 在 System.Environment.get_StackTrace() 在 System.Diagnostics.TraceEventCache.get_Callstack() 在 System.Diagnostics.TraceListener.WriteFooter(TraceEventCache eventCache) 在 System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String message) 在 Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.TraceInternal(TraceEventType eventType, String message) 在 Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.LogError(String message, Exception exception, Object[] args) 在 System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Filters.ExceptionFilterAttribute.<ExecuteExceptionFilterAsyncCore>d__0.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Filters.ExceptionFilterAttribute.ExecuteExceptionFilterAsyncCore(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Filters.ExceptionFilterAttribute.System.Web.Http.Filters.IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Controllers.ExceptionFilterResult.ExecuteAsync(CancellationToken cancellationToken) 在 System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 在 System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
至此,webapi加密工做已經所有完成,上述異常是直接訪問url報的錯誤,必須在app環境下才能夠正常訪問。
總結:webapi加密機密不少,像微信小程序,用戶很難拿到客戶端app的源碼,想知道咱們的key也是無從提及。固然,咱們也得按期更新app版本。
像app for andriod or ios 可使用雙向證書,或者使用咱們上述的方式,而後加固app,防止不懷好意的人破解獲得key,固然無論如何,咱們首先要走的都是https協議!