请求的时候
string appid = "appid"; string appkey = "123132132132312"; string token = CommonAPI.CreateSASToken(appid, appkey, TimeSpan.FromSeconds(120)); string url = "xxxxx" + "?" + token;
方法
public static string CreateSASToken(string appid, string appkey, TimeSpan timeout) { var values = new Dictionary<string, string> { { "once", CreateRandCode(8) }, { "appid", appid }, { "expiry", (DateTimeOffset.UtcNow + timeout).ToUnixTimeSeconds().ToString() } }; //给values里的key值排序 var signContent = string.Join("", values.OrderBy(pair => pair.Key).Select(pair => pair.Key + pair.Value)); string sign; using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(appkey))) { sign = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(signContent))); } //var para = string.Join("&", values.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}={HttpUtility.UrlEncode(pair.Value)}")); var para = string.Join("&", values.OrderBy(pair => pair.Key).Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value))); //return $"{para}&token={HttpUtility.UrlEncode(sign)}"; return para + "&token=" + HttpUtility.UrlEncode(sign); } private static int Random(int maxValue) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); decimal _base = (decimal)long.MaxValue; byte[] rndSeries = new byte[8]; rng.GetBytes(rndSeries); return (int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * maxValue); } public static string CreateRandCode(int codeLen) { string keySet = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int keySetLength = keySet.Length; StringBuilder str = new StringBuilder(keySetLength); for (int i = 0; i < codeLen; ++i) { str.Append(keySet[Random(keySetLength)]); } return str.ToString(); }
验证Token
public async Task<ActionResult> ActionName(string appid, string expiry, string once, string token, Models.Student student) { var keyname = new string[]{"appkey"}; var setting = _db.BaseSetting.Where(p => p.AppId == $"{appid}" &&keyname.Contains(p.KeyName)).ToDictionary(p => p.KeyName, p => p.KeyValue); var appkey=setting["appkey"]; //Validate Token if (ValidateSASToken(appid,appkey, expiry, once, token) == false) throw new Exception($"token错误!"); }
public static bool ValidateTimeout(string UnixTimeSec) { DateTimeOffset sdate = DateTimeOffset.UtcNow; DateTimeOffset edate = sdate.AddMinutes(TokenTimeOutMinute); DateTimeOffset mydate = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt32(UnixTimeSec)); if (mydate >= sdate && mydate <= edate) { return true; } else return false; } public static Boolean ValidateSASToken(string appid, string appkey, string expiry, string once, string token) { if (ValidateTimeout(expiry)) { var values = new Dictionary<string, string> { { "once", once }, { "appid", appid }, { "expiry", expiry } }; var signContent = string.Join("", values.OrderBy(pair => pair.Key).Select(pair => pair.Key + pair.Value)); string sign; using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(appkey))) { sign = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(signContent))); } return token == sign; } else return false; }
其实这个token的验证的方法不是那么的麻烦:
请求方请求的Values 的值,带过来在服务端根据Values再重新生成一下,
然后对比:请求端的token是否等于在服务端重新生成的token,如此对比。
时间戳: