zoukankan      html  css  js  c++  java
  • SASToken

    请求的时候

    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,如此对比。

    时间戳

    人各有命,上天注定,有人天生为王,有人落草为寇。脚下的路,如果不是你自己的选择,那么旅程的终点在哪,也没人知道。你会走到哪,会遇到谁,都不一定。
  • 相关阅读:
    学习Py——自己模拟写的一个Range功能
    心情随笔20180529
    记一次排查局网内的ARP包 “不存在的” MAC 地址及 “不存在的”IP 所发的ARP包
    最长反链
    浅谈矩阵树定理
    毒瘤dp 学校食堂
    P3565 由简单的树形dp 引入 长链刨分
    noi 2017 整数
    记人生的抉择
    2019 HL SC day10
  • 原文地址:https://www.cnblogs.com/ZkbFighting/p/14336817.html
Copyright © 2011-2022 走看看