1、token值生成方式一: 由接口提供方提供获取token的接口,调用方只需传输参数相应的参数即可
url:http://******?action=GetToken&appid=***&secret=****
通过appid与secret 值获取服务器提供的token值
public object GetToken(HttpContext context)
{
Dictionary<object, object> dic = new Dictionary<object, object>();
try
{
string appid = InputText(context.Request.QueryString["appid"]);
string secret = InputText(context.Request.QueryString["secret"]);
if (appid != null && secret != null)
{
string token = string.Empty;
//验证appid 和 secret 是否有效
if (VerificationAppID(appid, secret))
{
//获取数据库中的token
DateTime creationtime = new DateTime();
int expires = 7200;
//token = XT.Base.EntityBase.GetDB().GetScale(string.Format("select token from ApiTokenConfig where appid='{0}' and appsecret='{1}'", appid, secret)).ToString();
DataTable dt = XT.Base.EntityBase.GetDB().GetDS(string.Format("select * from ApiTokenConfig where appid='{0}' and appsecret='{1}'", appid, secret)).Tables[0];
if (dt.Rows.Count > 0)
{
expires = int.Parse(dt.Rows[0]["expires"].ToString());
token = dt.Rows[0]["token"].ToString();
//判断token是否失效
if (VerificationToken(token) && token != "")
{
dic.Add("code", "0");
dic.Add("msg", "操作成功");
dic.Add("result", "1");
dic.Add("token", dt.Rows[0]["token"].ToString());
dic.Add("creationtime", dt.Rows[0]["creationtime"]);
dic.Add("expires", dt.Rows[0]["expires"]);
}
else
{
string tokenkey = RandomCode.GetRandomCodeByLength(6);
//token = XT.Utility.EncryptObject.EncryptString(XT.Utility.EncryptObject.Encrypt(appid + secret, tokenkey));
token = XT.Utility.EncryptObject.Encrypt(appid + secret, tokenkey);
creationtime = DateTime.Now;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("update ApiTokenConfig set token='{0}',tokenkey='{1}',creationtime='{2}' where appid='{3}' and appsecret='{4}'", token, tokenkey, creationtime, appid, secret);
XT.Base.EntityBase.GetDB().ExcuteSql(sb.ToString());
dic.Add("code", "0");
dic.Add("msg", "操作成功");
dic.Add("result", "1");
dic.Add("token", token);
dic.Add("creationtime", creationtime);
dic.Add("expires", expires);
}
}
else
{
dic.Add("code", "10001");
dic.Add("msg", "appid与appsecret不匹配!");
dic.Add("result", "0");
}
}
else
{
dic.Add("code", "10001");
dic.Add("msg", "appid与appsecret不匹配!");
dic.Add("result", "0");
}
}
else
{
//Rlt = AjaxResult.Error("请检查appid或appsecret是否有效!");
dic.Add("code", "10000");
dic.Add("msg", "不合法的appid或appsecret");
dic.Add("result", "0");
}
}
catch (Exception ex)
{
//Rlt = AjaxResult.Error("异常错误:" + ex.Message);
dic.Add("code", "11111");
dic.Add("msg", "异常错误:" + ex.Message);
dic.Add("result", "0");
}
return dic;
}
注:时效性:int expires = 7200; 7200s=2小时 如上图代码 若时间超过两小时则重新生成token,下面为生成token代码:
参数Text : key和secret字符串 参数skey:六位随机字母或者数字
public static string Encrypt(string Text, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(Text);
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
skey 生成方式:
public class RandomCode
{
public RandomCode()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
public static string GetRandomCodeByLength(int strLength)
{
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
Random rd = new Random();
for (int i = 0; i < strLength; i++)
{
newRandom.Append(constant[rd.Next(62)]);
}
return newRandom.ToString();
}
}
注:由于时效性和skey的随机性这样就保证了数据传输的安全性。
2、token生成方式二: 将需要传输的数据字符串和接口提供方提供的key字符串 然后MD5加密 生成token
调接口:
/// <summary>
/// 接收勘察结果
/// </summary>
/// <param name="postData"></param>
/// <returns></returns>
public static string installedNotice(Dictionary<string ,object> dicpostData)
{
string jsontoken = XT.Utility.EncryptObject.UnicodeToGB(JSONHelper.ToJson(dicpostData));
string md5token = XT.Utility.EncryptObject.GetMD5(token + jsontoken);
string postData = "&token=" + md5token + "&postData=" + jsontoken;
string strUrl = "installedNotice.pub";
string htmlUrl = string.Format("{0}{1}",url,strUrl);
return Web_Request.POST_WebRequestHTML(encodingName, htmlUrl, postData);
}
上面代码中的变量token是一个固定值(提供接口方给的), 参数dicpostData为传输的json字符串。
token生成:
public static string GetMD5(string myString)
{
string _str1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(myString, "MD5");
return _str1;
}
如此便生成了我们调用接口的凭证token,这种方式生成的token也绝对是安全的,对方验证token的方式也是拿到数据之后MD5验证我这边传输过去的token值和他那边生成的token值是否一致,从而确定有效性。
注:最近作者面试遇到有面试官质疑MD5不能反编译,拿不到传输json数据,我当时也是脑抽了,没有解释json数据是作为另一个参数传递的。故而。。。。。(不多聊)
3、token生成方式三:直接上代码【跟第二种区别不是很大】
public static string PushStore(string storecode, string storename, string parentstorecode, string parentstorename, string address)
{
try
{
IDictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("app_key", app_key);
dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dic.Add("store_name", storename);
dic.Add("address", address);
dic.Add("store_id", storecode);
dic.Add("org_code", parentstorecode);
dic.Add("org_name", parentstorename);
dic.Add("status", "0");
string sign = GetSignString(dic, appsecreate);
dic.Add("sign", sign);
string postData = XT.Utility.EncryptObject.UnicodeToGB(JSONHelper.ToJson(dic));
string htmlUrl = string.Format("{0}{1}", url, "AddStore");
string str = Web_Request.POST_WebRequestHTML("utf-8", htmlUrl, postData, "");
string strnew = str.Substring(18, str.Length - 19);
error_response jo = JsonMapper.ToObject<error_response>(strnew);
return jo.sub_msg;
}
catch (Exception ex)
{
return ex.ToString();
}
public static string GetSignString(IDictionary<string, string> sortedParams, string appSecret)
{
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
//把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder();
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
query.Append(key).Append(value);
}
}
query.Append(appSecret);
//修改部分
query.ToString();
//第三步:使用MD5加密
byte[] bytes;
MD5 md5 = MD5.Create();
bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
// 第四步:把二进制转化为大写的十六进制
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
result.Append(bytes[i].ToString("X2"));
}
return result.ToString();
}
也是数据把传输数据封装之后MD5,仅有的区别是:这里把给的固定值secret直接放到了json字符串内。实质上第二种第三种是一种验证方式。