1. 程式人生 > >asp.net webapi 自定義身份驗證

asp.net webapi 自定義身份驗證

auth 服務端 ati end 驗證 rri span acc amp

/// <summary>
/// 驗證
/// </summary>
/// Account API賬號
/// TimeStamp 請求時間
/// Sign 所有請求參數 加密
public class AuthFilterOutside : AuthorizeAttribute
{
  //重寫基類的驗證方式,加入我們自定義的Ticket驗證
  public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
  {
    //url獲取token
    var
content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;     string account = content.Request.QueryString["Account"];     string sign = content.Request.QueryString["Sign"];     int timeStamp = 0;     int.TryParse(content.Request.QueryString["TimeStamp"], out timeStamp);     ApiInfo apiInfo
= DB.GetApiInfo(account);     int nowTimeStamp = Convert.ToInt32(GenerateTimeStamp());     // 無效請求     if (apiInfo == null || nowTimeStamp - timeStamp > 15)     {       HandleUnauthorizedRequest(actionContext);       return;     }     SortedDictionary<string, string> dic = new SortedDictionary<string
, string>();     foreach (string key in content.Request.QueryString.AllKeys)     {       if (key != "sign")       {         dic.Add(key, content.Request.QueryString[key]);       }     }     string makeSign = GetMakeSign(dic, apiInfo.Token);     // 簽名不正確     if (sign != makeSign)     {       HandleUnauthorizedRequest(actionContext);       return;     }   }   protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)   {     base.HandleUnauthorizedRequest(filterContext);     var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();     response.StatusCode = HttpStatusCode.Forbidden;     string str = "{\"success\":\"false\",\"message\":\"服務端拒絕訪問:您沒有權限!\"}";     response.Content = new StringContent(str, Encoding.UTF8, "application/json");   }   public static string GenerateTimeStamp()   {     TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);     return Convert.ToInt64(ts.TotalSeconds).ToString();   }   /// <summary>   /// 所有參數 ascii碼排序 最後追加Key   /// </summary>   /// <param name="dic"></param>   /// <param name="token"></param>   /// <returns></returns>   public string GetMakeSign(SortedDictionary<string, string> dic, string token)   {     StringBuilder strBuilder = new StringBuilder();     foreach (var item in dic)     {       strBuilder.AppendFormat("{0}={1}&", item.Key, item.Value);     }     strBuilder.AppendFormat("key={0}", token);     var md5 = MD5.Create();     var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(strBuilder.ToString()));     var sb = new StringBuilder();     foreach (byte b in bs)     {       sb.Append(b.ToString("x2"));     }     //所有字符轉為大寫     return sb.ToString().ToUpper();   } }

asp.net webapi 自定義身份驗證