国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net mvc webapi 實用的接口加密方法示例

2024-07-10 13:32:43
字體:
來源:轉載
供稿:網友

在很多項目中,因為webapi是對外開放的,這個時候,我們就要得考慮接口交換數據的安全性。

安全機制也比較多,如andriod與webapi 交換數據的時候,可以走雙向證書方法,但是開發成本比較大,

今天我們不打算介紹這方面的知識,我們說說一個較簡單也較常見的安全交換機

在這里要提醒讀者,目前所有的加密機制都不是絕對的安全

我們的目標是,任何用戶或者軟件獲取到我們的webapi接口url后用來再次訪問該地址都是無效的!

達到這種目標的話,我們必須要在url中增加一個時間戳,但是僅僅如此還是不夠,用戶可以修改我們的時間戳!

因此我們可以對時間戳 進行MD5加密,但是這樣依然不夠,用戶可以直接對我們的時間戳md5的哦,因些需要引入一個絕對安全

的雙方約定的key,并同時加入其它參數進行混淆!

注意:這個key要在app里和我們的webapi里各保存相同的一份!

于是我們約定公式: 加密結果=md5(時間戳+隨機數+key+post或者get的參數)

下面我們開始通過上述公式寫代碼:

于由我的環境是asp.net mvc 的,所以重寫一個加密類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))    throw new SecurityException();

2、判斷時間戳是否超過指定時間

 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 三種方式提取參數

 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 方式提取參數

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、排序上述參數并拼接,形成我們要參與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(" ", "");   }

6、開始約定公式計算結果并對比傳過的結果是否一致

 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 里加入配置上述類

 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、添加寫入日志類

 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、利用微信小程序測試接口

 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, "");}

10、測試日志

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()失敗的程序集的區域是: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加密工作已經全部完成,上述異常是直接訪問url報的錯誤,必須在app環境下才可以正常訪問。

 總結:webapi加密機密很多,像微信小程序,用戶很難拿到客戶端app的源碼,想知道我們的key也是無從說起。當然,我們也得定期更新app版本。

像app for andriod or ios 可以使用雙向證書,或者使用我們上述的方式,然后加固app,防止不懷好意的人破解得到key,當然不管如何,我們首先要走的都是https協議!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到ASP.NET教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西华县| 沙湾县| 同心县| 镇安县| 民县| 蛟河市| 曲松县| 石城县| 吉林省| 康马县| 久治县| 翁源县| 金昌市| 宁强县| 科技| 东乌| 益阳市| 易门县| 咸阳市| 勐海县| 鄂托克前旗| 阳西县| 布拖县| 关岭| 新宁县| 宜兰市| 灵寿县| 兴宁市| 长顺县| 墨竹工卡县| 安阳县| 买车| 定结县| 保康县| 淮阳县| 闸北区| 泸定县| 察哈| 金塔县| 孙吴县| 印江|