asp.net mvc webapi 实用的接口加密方法示例
在很多项目中,因为webapi是对外开放的,这个时候,我们就要得考虑接口交换数据的安全性。
安全机制也比较多,如andriod与webapi交换数据的时候,可以走双向证书方法,但是开发成本比较大,
今天我们不打算介绍这方面的知识,我们说说一个较简单也较常见的安全交换机制
在这里要提醒读者,目前所有的加密机制都不是绝对的安全!
我们的目标是,任何用户或者软件获取到我们的webapi接口url后用来再次访问该地址都是无效的!
达到这种目标的话,我们必须要在url中增加一个时间戳,但是仅仅如此还是不够,用户可以修改我们的时间戳!
因此我们可以对时间戳进行MD5加密,但是这样依然不够,用户可以直接对我们的时间戳md5的哦,因些需要引入一个绝对安全
的双方约定的key,并同时加入其它参数进行混淆!
注意:这个key要在app里和我们的webapi里各保存相同的一份!
于是我们约定公式:加密结果=md5(时间戳+随机数+key+post或者get的参数)
下面我们开始通过上述公式写代码:
于由我的环境是asp.netmvc的,所以重写一个加密类ApiSecurityFilter
1、获取参数
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)) thrownewSecurityException();
2、判断时间戳是否超过指定时间
doublets=0; booltimespanvalidate=double.TryParse(timestamp,outts); boolfalg=(DateTime.UtcNow-newDateTime(1970,1,1,0,0,0,0)).TotalMilliseconds-ts>60*1000; if(falg||(!timespanvalidate)) thrownewSecurityException();
3、POST/DELETE/UPDATE三种方式提取参数
case"POST": case"PUT": case"DELETE": Streamstream=HttpContext.Current.Request.InputStream; StreamReaderstreamReader=newStreamReader(stream); sortedParams=newSortedDictionary(newJsonSerializer().Deserialize >(newJsonTextReader(streamReader))); break;
4、GET方式提取参数
case"GET": IDictionaryparameters=newDictionary (); foreach(stringkeyinHttpContext.Current.Request.QueryString) { if(!string.IsNullOrEmpty(key)) { parameters.Add(key,HttpContext.Current.Request.QueryString[key]); } } sortedParams=newSortedDictionary (parameters); break;
5、排序上述参数并拼接,形成我们要参与md5的约定公式中的第四个参数
StringBuilderquery=newStringBuilder(); if(sortedParams!=null) { foreach(varsortinsortedParams.OrderBy(k=>k.Key)) { if(!string.IsNullOrEmpty(sort.Key)) { query.Append(sort.Key).Append(sort.Value); } } data=query.ToString().Replace("",""); }
6、开始约定公式计算结果并对比传过的结果是否一致
varmd5Staff=Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp+nonce+staffId+data),32); if(!md5Staff.Equals(signature)) thrownewSecurityException();
完整的代码如下:
publicclassApiSecurityFilter:ActionFilterAttribute { publicoverridevoidOnActionExecuting(HttpActionContextactionContext) { varrequest=actionContext.Request; varmethod=request.Method.Method; varstaffId="^***********************************$"; stringtimestamp=string.Empty,nonce=string.Empty,signature=string.Empty; if(request.Headers.Contains("timestamp")) timestamp=request.Headers.GetValues("timestamp").FirstOrDefault(); if(request.Headers.Contains("nonce")) nonce=request.Headers.GetValues("nonce").FirstOrDefault(); if(request.Headers.Contains("signature")) signature=request.Headers.GetValues("signature").FirstOrDefault(); if(string.IsNullOrEmpty(timestamp)||string.IsNullOrEmpty(nonce)||string.IsNullOrEmpty(signature)) thrownewSecurityException(); doublets=0; booltimespanvalidate=double.TryParse(timestamp,outts); boolfalg=(DateTime.UtcNow-newDateTime(1970,1,1,0,0,0,0)).TotalMilliseconds-ts>60*1000; if(falg||(!timespanvalidate)) thrownewSecurityException("timeSpanValidate"); vardata=string.Empty; IDictionarysortedParams=null; switch(method.ToUpper()) { case"POST": case"PUT": case"DELETE": Streamstream=HttpContext.Current.Request.InputStream; StreamReaderstreamReader=newStreamReader(stream); sortedParams=newSortedDictionary (newJsonSerializer().Deserialize >(newJsonTextReader(streamReader))); break; case"GET": IDictionary parameters=newDictionary (); foreach(stringkeyinHttpContext.Current.Request.QueryString) { if(!string.IsNullOrEmpty(key)) { parameters.Add(key,HttpContext.Current.Request.QueryString[key]); } } sortedParams=newSortedDictionary (parameters); break; default: thrownewSecurityException("defaultOptions"); } StringBuilderquery=newStringBuilder(); if(sortedParams!=null) { foreach(varsortinsortedParams.OrderBy(k=>k.Key)) { if(!string.IsNullOrEmpty(sort.Key)) { query.Append(sort.Key).Append(sort.Value); } } data=query.ToString().Replace("",""); } varmd5Staff=Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp+nonce+staffId+data),32); if(!md5Staff.Equals(signature)) thrownewSecurityException("md5Staff"); base.OnActionExecuting(actionContext); } publicoverridevoidOnActionExecuted(HttpActionExecutedContextactionExecutedContext) { base.OnActionExecuted(actionExecutedContext); } }
7、最后在asp.netmvc里加入配置上述类
publicstaticclassWebApiConfig { publicstaticvoidRegister(HttpConfigurationconfig) { //WebAPIconfigurationandservices config.Filters.Add(newApiSecurityFilter()); config.Filters.Add(newApiHandleErrorAttribute()); //WebAPIroutes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name:"DefaultApi", routeTemplate:"api/{controller}/{id}", defaults:new{id=RouteParameter.Optional} ); } }
8、添加写入日志类
publicclassApiHandleErrorAttribute:ExceptionFilterAttribute { //////addbylaiyunba /// ///contextoop publicoverridevoidOnException(HttpActionExecutedContextfilterContext) { LoggerFactory.CreateLog().LogError(Messages.error_unmanagederror,filterContext.Exception); } }
9、利用微信小程序测试接口
vardata={ UserName:username, Password:password, Action:'Mobile', Sms:'' }; vartimestamp=util.gettimestamp(); varnonce=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函数:
functiongetMD5Staff(queryData,timestamp,nonce){ varstaffId=getstaffId();//保存的key与webapi同步 vardata=dictionaryOrderWithData(queryData); returnmd5.md5(timestamp+nonce+staffId+data); }
2)dictionaryOrderWithData函数:
functiondictionaryOrderWithData(dic){ //eg{x:2,y:3,z:1} varresult=""; varsdic=Object.keys(dic).sort(function(a,b){returna.localeCompare(b)}); varvalue=""; for(varkiinsdic){ if(dic[sdic[ki]]==null){ value="" } else{ value=dic[sdic[ki]]; } result+=sdic[ki]+value; } returnresult.replace(/\s/g,""); }
10、测试日志
LaiyunbaAppError:2:2017-10-1809:15:25Unmanagederrorinaplication,theexceptioninformationisException:System.Security.SecurityException:安全性错误。 在DistributedServices.MainBoundedContext.FilterAttribute.ApiSecurityFilter.OnActionExecuting(HttpActionContextactionContext) 在System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutingAsync(HttpActionContextactionContext,CancellationTokencancellationToken) ---引发异常的上一位置中堆栈跟踪的末尾--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Tasktask) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Tasktask) 在System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() ---引发异常的上一位置中堆栈跟踪的末尾--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Tasktask) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Tasktask) 在System.Web.Http.Controllers.ActionFilterResult. d__2.MoveNext() ---引发异常的上一位置中堆栈跟踪的末尾--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Tasktask) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Tasktask) 在System.Web.Http.Controllers.ExceptionFilterResult. d__0.MoveNext() 失败的程序集的区域是: MyComputer LogicalOperationStack=2017-10-1809:15:25 2017-10-1809:15:25DateTime=2017-10-18T01:15:25.1000017Z 2017-10-1809:15:25Callstack=在System.Environment.GetStackTrace(Exceptione,BooleanneedFileInfo) 在System.Environment.get_StackTrace() 在System.Diagnostics.TraceEventCache.get_Callstack() 在System.Diagnostics.TraceListener.WriteFooter(TraceEventCacheeventCache) 在System.Diagnostics.TraceSource.TraceEvent(TraceEventTypeeventType,Int32id,Stringmessage) 在Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.TraceInternal(TraceEventTypeeventType,Stringmessage) 在Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.LogError(Stringmessage,Exceptionexception,Object[]args) 在System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync(HttpActionExecutedContextactionExecutedContext,CancellationTokencancellationToken) 在System.Web.Http.Filters.ExceptionFilterAttribute. d__0.MoveNext() 在System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine&stateMachine) 在System.Web.Http.Filters.ExceptionFilterAttribute.ExecuteExceptionFilterAsyncCore(HttpActionExecutedContextactionExecutedContext,CancellationTokencancellationToken) 在System.Web.Http.Filters.ExceptionFilterAttribute.System.Web.Http.Filters.IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContextactionExecutedContext,CancellationTokencancellationToken) 在System.Web.Http.Controllers.ExceptionFilterResult. d__0.MoveNext() 在System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&stateMachine) 在System.Web.Http.Controllers.ExceptionFilterResult.ExecuteAsync(CancellationTokencancellationToken) 在System.Web.Http.ApiController.ExecuteAsync(HttpControllerContextcontrollerContext,CancellationTokencancellationToken) 在System.Web.Http.Dispatcher.HttpControllerDispatcher. d__1.MoveNext() 在System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine&stateMachine) 在System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessagerequest,CancellationTokencancellationToken) 在System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessagerequest,CancellationTokencancellationToken) 在System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessagerequest,CancellationTokencancellationToken)
至此,webapi加密工作已经全部完成,上述异常是直接访问url报的错误,必须在app环境下才可以正常访问。
总结:webapi加密机密很多,像微信小程序,用户很难拿到客户端app的源码,想知道我们的key也是无从说起。当然,我们也得定期更新app版本。
像appforandriodorios可以使用双向证书,或者使用我们上述的方式,然后加固app,防止不怀好意的人破解得到key,当然不管如何,我们首先要走的都是https协议!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。