码迷,mamicode.com
首页 > Windows程序 > 详细

asp.net webapi 自定义身份验证

时间:2018-10-08 11:28:21      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:end   control   date   dict   bytes   inf   TBase   parse   ict   

/// <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 自定义身份验证

标签:end   control   date   dict   bytes   inf   TBase   parse   ict   

原文地址:https://www.cnblogs.com/xuannian/p/9708521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!