在很多項(xiàng)目中,因?yàn)閣ebapi是對(duì)外開(kāi)放的,這個(gè)時(shí)候,我們就要得考慮接口交換數(shù)據(jù)的安全性。
安全機(jī)制也比較多,如andriod與webapi 交換數(shù)據(jù)的時(shí)候,可以走雙向證書(shū)方法,但是開(kāi)發(fā)成本比較大,
今天我們不打算介紹這方面的知識(shí),我們說(shuō)說(shuō)一個(gè)較簡(jiǎn)單也較常見(jiàn)的安全交換機(jī)制
在這里要提醒讀者,目前所有的加密機(jī)制都不是絕對(duì)的安全!
我們的目標(biāo)是,任何用戶(hù)或者軟件獲取到我們的webapi接口url后用來(lái)再次訪問(wèn)該地址都是無(wú)效的!
達(dá)到這種目標(biāo)的話(huà),我們必須要在url中增加一個(gè)時(shí)間戳,但是僅僅如此還是不夠,用戶(hù)可以修改我們的時(shí)間戳!
因此我們可以對(duì)時(shí)間戳 進(jìn)行MD5加密,但是這樣依然不夠,用戶(hù)可以直接對(duì)我們的時(shí)間戳md5的哦,因些需要引入一個(gè)絕對(duì)安全
的雙方約定的key,并同時(shí)加入其它參數(shù)進(jìn)行混淆!
注意:這個(gè)key要在app里和我們的webapi里各保存相同的一份!
于是我們約定公式: 加密結(jié)果=md5(時(shí)間戳+隨機(jī)數(shù)+key+post或者get的參數(shù))
下面我們開(kāi)始通過(guò)上述公式寫(xiě)代碼:
于由我的環(huán)境是asp.net mvc 的,所以重寫(xiě)一個(gè)加密類(lèi)ApiSecurityFilter
1、獲取參數(shù)
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();
2、判斷時(shí)間戳是否超過(guò)指定時(shí)間
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();
3、POST/DELETE/UPDATE 三種方式提取參數(shù)
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;
4、GET 方式提取參數(shù)
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;
5、排序上述參數(shù)并拼接,形成我們要參與md5的約定公式中的第四個(gè)參數(shù)
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(" ", ""); }
6、開(kāi)始約定公式計(jì)算結(jié)果并對(duì)比傳過(guò)的結(jié)果是否一致
var md5Staff = Seedwork.Utils.CharHelper.MD5(string.Concat(timestamp + nonce + staffId + data), 32); if (!md5Staff.Equals(signature)) throw new SecurityException();
完整的代碼如下:
public class ApiSecurityFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var request = actionContext.Request; var method = request.Method.Method; var staffId = "^***********************************$"; string timestamp = 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)) 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("timeSpanValidate"); var data = string.Empty; IDictionary<string, string> sortedParams = null; switch (method.ToUpper()) { 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; 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; default: throw new SecurityException("defaultOptions"); } 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("md5Staff"); base.OnActionExecuting(actionContext); } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { base.OnActionExecuted(actionExecutedContext); } }
7、最后在asp.net mvc 里加入配置上述類(lèi)
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 } ); } }
8、添加寫(xiě)入日志類(lèi)
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); } }
9、利用微信小程序測(cè)試接口
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)其中g(shù)etMD5Staff函數(shù):
function getMD5Staff(queryData, timestamp, nonce) { var staffId = getstaffId();//保存的key與webapi同步 var data = dictionaryOrderWithData(queryData); return md5.md5(timestamp + nonce + staffId + data);}
2)dictionaryOrderWithData函數(shù):
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, "");}
10、測(cè)試日志
LaiyunbaApp Error: 2 : 2017-10-18 09:15:25 Unmanaged error in aplication, the exception information is Exception:System.Security.SecurityException: 安全性錯(cuò)誤。 在 DistributedServices.MainBoundedContext.FilterAttribute.ApiSecurityFilter.OnActionExecuting(HttpActionContext actionContext) 在 System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)--- 引發(fā)異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()--- 引發(fā)異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()--- 引發(fā)異常的上一位置中堆棧跟蹤的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()失敗的程序集的區(qū)域是:MyComputerLogicalOperationStack=2017-10-18 09:15:25 2017-10-18 09:15:25 DateTime=2017-10-18T01:15:25.1000017Z2017-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加密工作已經(jīng)全部完成,上述異常是直接訪問(wèn)url報(bào)的錯(cuò)誤,必須在app環(huán)境下才可以正常訪問(wèn)。
總結(jié):webapi加密機(jī)密很多,像微信小程序,用戶(hù)很難拿到客戶(hù)端app的源碼,想知道我們的key也是無(wú)從說(shuō)起。當(dāng)然,我們也得定期更新app版本。
像app for andriod or ios 可以使用雙向證書(shū),或者使用我們上述的方式,然后加固app,防止不懷好意的人破解得到key,當(dāng)然不管如何,我們首先要走的都是https協(xié)議!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選