asp.net webapi 自定义身份验证

/// 
/// 验证
/// 
/// Account API账号
/// TimeStamp 请求时间
/// Sign 所有请求参数 加密
public class AuthFilterOutside : AuthorizeAttribute
{
  //重写基类的验证方式,加入我们自定义的Ticket验证
  public override void OnAuthorization(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();
  }
  /// 
  /// 所有参数 ascii码排序 最后追加Key
  /// 
  /// 
  /// 
  /// 
  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();
  }
}

 

转载于:https://www.cnblogs.com/xuannian/p/9708521.html

你可能感兴趣的:(asp.net webapi 自定义身份验证)