当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net webapi 自定义身份验证

asp.net webapi 自定义身份验证

2018年10月08日  | 移动技术网IT编程  | 我要评论

野蛮控卫,锡盟西乌旗,黄页大全

/// <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();
  }
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网