欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net webapi 自定义身份验证

程序员文章站 2022-12-25 14:07:20
/// /// 验证 /// /// Account API账号 /// TimeStamp 请求时间 /// Sign 所有请求参数 加密 public class AuthFilterOutside : AuthorizeAttribute { //重写基类的验证方式,加入我们自定义的Ticke... ......
/// <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();
  }
}