zoukankan      html  css  js  c++  java
  • WebApiHelper

    /// <summary>
            /// 根据token过滤
            /// </summary>
            /// <param name="list"></param>
            /// <returns></returns>
            private List<train_code_list> GetListByToken(List<train_code_list> list)
            {
                //token
                var token = System.Web.HttpContext.Current.Request.Headers["Token"];
                if (!string.IsNullOrEmpty(token))
                {
                    var station = (new DESHelper().DecryptString(((new DESHelper().DecryptString(token, DESHelper.key, DESHelper.iv)).Split('/')[3]), DESHelper.key, DESHelper.iv));
                    list = list.Where(c => c.Detail.Any(p => p.station_name == station)).ToList();
                }
                return list;
            }
     /// <summary>
            /// 获取随机码
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public ResultMsg GetRandom(authentication data)
            {
                var resultMsg = new ResultMsg() { Status = false, Info = "", Data = data };
                try
                {
                    if (string.IsNullOrEmpty(data.UniqueCode))
                    {
                        resultMsg.Info = "唯一码为空!";
                        return resultMsg;
                    }
                    if (string.IsNullOrEmpty(data.PID))
                    {
                        resultMsg.Info = "PID为空!";
                        return resultMsg;
                    }
                    if (string.IsNullOrEmpty(data.PIN))
                    {
                        resultMsg.Info = "PIN为空!";
                        return resultMsg;
                    }
    
                    var query = Query.And(Query.EQ("UniqueCode", data.UniqueCode),Query.EQ("PID", data.PID),Query.EQ("PIN", data.PIN));
                    if (Mb.FindOne<authentication>(query) != null)
                    {
                        var strRandom= getStr(6);
                        if (Mb.Update<authentication>(query, Update.Set("RandomDigit", strRandom)))
                        {
                            resultMsg.Status = true;
                            resultMsg.Data = strRandom;
                        }
                        else
                        {
                            resultMsg.Info = "保存随机数失败!";
                        }                    
                    }
                    else
                    {
                        resultMsg.Info = "提供的信息在数据库中不存在!";
                    }
                }
                catch (Exception ex)
                {
                    resultMsg.Info = ex.Message;
                }
                return resultMsg;
            }
    /// <summary>
            /// 获取token
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public ResultMsg GetToken(authentication data)
            {
                var resultMsg = new ResultMsg() { Status = false, Info = "", Data = data };
                try
                {
                    if (string.IsNullOrEmpty(data.UniqueCode))
                    {
                        resultMsg.Info = "唯一码为空!";
                        return resultMsg;
                    }               
    
                    if (string.IsNullOrEmpty(data.EncryptedStorage))
                    {
                        resultMsg.Info = "加密存储区信息为空!";
                        return resultMsg;
                    }
    
                    var auth = Mb.FindOne<authentication>(Query.EQ("UniqueCode", data.UniqueCode));                              
    
                    if (auth != null)
                    {
                        if (data.EncryptedStorage.Replace("", "") != auth.EncryptedStorage)
                        {
                            resultMsg.Info = "加密存储区信息与数据库中信息不匹配!";
                            return resultMsg;
                        }
                        if (!ValidateMsg(auth, data.EcryptedSMS, resultMsg))
                        {
                            return resultMsg;
                        }
    
                        if (Mb.Remove<token>(Query.EQ("UniqueCode", data.UniqueCode)))
                        {
                            var token = new token()
                            {
                                UniqueCode = data.UniqueCode,
                                SignToken = new DESHelper().EncryptString(data.UniqueCode + "/" + Guid.NewGuid().ToString() + "/" + DateTime.Now.AddHours(2).ToString("yyyy-MM-dd HH:mm:ss")
                                +"/"+ auth.EncryptedStorage, DESHelper.key, DESHelper.iv)
                            };
                           
                            //插入数据库
                            if (Mb.Insert<token>(token))
                            {
                                resultMsg.Status = true;
                                resultMsg.Data = token.SignToken;
                            }
                            else {
                                resultMsg.Info = "保存新的token发生异常!";
                            }                        
                        }
                        else {
                            resultMsg.Info = "删除旧的token发生异常!";
                        }                    
                    }
                    else{
                        resultMsg.Info = "提供的信息在数据库中不存在!";
                    }
                }
                catch (Exception ex)
                {
                    resultMsg.Info = ex.Message;
                }
                return resultMsg;      
            }
     /// <summary>
            /// 验证token
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public ResultMsg ValidateToken(string data)
            {
                var resultMsg = new ResultMsg() { Status = false, Info = "", Data = data };
                try
                {
                    var arrToken = (new DESHelper().DecryptString(data, DESHelper.key, DESHelper.iv)).Split('/');
    
                    if (arrToken.Length != 4)
                    {
                        resultMsg.Info = "token无效";
                        return resultMsg;
                    }
                    var auth = Mb.FindOne<authentication>(Query.And(Query.EQ("UniqueCode", arrToken[0]), Query.EQ("EncryptedStorage", arrToken[3].Replace("", ""))));
                    if (auth==null)
                    {
                        resultMsg.Info = "加密存储区信息与数据库中信息不匹配";
                        return resultMsg;
                    }
                    if (DateTime.Now.CompareTo(Convert.ToDateTime(arrToken[2])) >= 0)
                    {
                        Mb.Update<authentication>(Query.EQ("UniqueCode", arrToken[0]), Update.Set("RandomDigit", ""));
                        //token失效
                        resultMsg.Info = "token失效";
                        return resultMsg;
                    }
    
                    var Info = Mb.FindOne<token>(Query.EQ("UniqueCode", arrToken[0]));
                    if (Info != null && Info.SignToken == data)
                    {
                        resultMsg.Status = true;
                    }
                    else
                    {
                        //token无效
                        resultMsg.Info = "token无效";
                    }
                }
                catch (Exception ex)
                {
                    resultMsg.Info = ex.Message;
                }
                return resultMsg; 
            }
    /// <summary>
            /// 对比加密信息
            /// </summary>
            /// <param name="auth"></param>
            /// <param name="ecryptedSMS"></param>
            /// <param name="resultMsg"></param>
            /// <returns></returns>
            private bool ValidateMsg(authentication auth, string ecryptedSMS, ResultMsg resultMsg)
            {
                if (string.IsNullOrEmpty(auth.RandomDigit))
                {
                    resultMsg.Info = "随机码为空!";
                    return false;
                }
                if (string.IsNullOrEmpty(auth.Key))
                {
                    resultMsg.Info = "秘钥为空!";
                    return false;
                }
    
                //服务端软件计算秘钥信息
                byte[] bytRandomCode;
                string strRandomCode = auth.RandomDigit;
                bytRandomCode = new byte[strRandomCode.Length];
                bytRandomCode = System.Text.Encoding.ASCII.GetBytes(strRandomCode);
                String strMD5Key = auth.Key;
                byte[] bytShortKey;
                bytShortKey = new byte[strMD5Key.Length];
                bytShortKey = System.Text.Encoding.ASCII.GetBytes(strMD5Key);
                byte keylen = byte.Parse(strMD5Key.Length.ToString());
                byte randomlen = byte.Parse(strRandomCode.Length.ToString());
    
                byte[] sbMd5Key = new byte[32];
                byte[] sbdigest = new byte[16];
    
                uint s_MD5_result = ET99_API.MD5_HMAC(ref bytRandomCode[0], strRandomCode.Length, ref bytShortKey[0], strMD5Key.Length, out sbMd5Key[0], out sbdigest[0]);
                if (s_MD5_result != ET99_API.ET_SUCCESS)
                {
                    resultMsg.Info = "计算加密信息失败!";
                    return false;
                }
                //获取 SN到文本
                string strSoftDigest = "";
                for (int i = 0; i < 16; ++i)
                {
                    strSoftDigest += string.Format("{0:X2}", sbdigest[i]);
                }
    
                //与客户端的加密信息进行对比     
                if (strSoftDigest != ecryptedSMS)
                {
                    resultMsg.Info = "认证失败!";
                    return false;
                }
    
                return true;
            }
    /// <summary>
            /// 时间转化
            /// </summary>
            /// <param name="dateTime"></param>
            /// <returns></returns>
            public string GetDateTime(string dateTime)
            {
                DateTime result;
                if (!DateTime.TryParse(dateTime, out result))
                {
                    dateTime = DateTime.Now.ToString("yyyy-MM-dd");
                }
                else
                {
                    dateTime = result.ToString("yyyy-MM-dd");
                }
                return dateTime;
            }
     /// <summary>
            /// 自定义WebApi返回类型
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static HttpResponseMessage toJson(Object obj)
            {
                String str;
                if (obj is String || obj is Char)
                {
                    str = obj.ToString();
                }
                else
                {
                    str = JsonConvert.SerializeObject(obj);
                }
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
     /// <summary>
            /// 获取随机数
            /// </summary>
            /// <param name="len"></param>
            /// <returns></returns>
            public string getStr(int len)
            {
                string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                StringBuilder sb = new StringBuilder();
                Random rd = new Random();
                for (int i = 0; i < len; i++)
                {
                    sb.Append(str.Substring(rd.Next(0, str.Length), 1));
                }
                return sb.ToString();
            }

     测试webapi使用Postman这个工具

    萌橙 你瞅啥?
  • 相关阅读:
    C++类构造函数初始化列表(转)
    Linux可重入函数和线程安全的区别与联系(转)
    Splinter自动登录
    VBA添加下拉菜单
    批处理自动备份并生成日志文件
    VBA 格式化excel数据表 (数据分列)
    Python 调用outlook发送邮件(转 )
    Node.js 文件操作
    Node.js express模块 http服务
    将ejs模板文件的后缀换成html
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/12082038.html
Copyright © 2011-2022 走看看