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(); } }
推荐阅读
-
ASP.NET Core自定义本地化教程之从文本文件读取本地化字符串
-
自定义Spring Security的身份验证失败处理方法
-
浅谈asp.net Forms身份验证详解
-
ASP.NET Core 2.2 WebApi 系列【六】泛型仓储模式
-
ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入
-
ASP.NET Core 2.2 WebApi 系列【四】集成Swagger
-
ASP.NET Core Web 应用程序开发期间部署到IIS自定义主机域名并附加到进程调试
-
Asp.net自定义控件系列(一)
-
在ASP.NET Core中显示自定义的错误页面
-
asp.net DataTable导出Excel自定义列名的方法