WebAPI接口调用身份验证
Common
1 public interface ICacheWriter 2 { 3 void AddCache(string key, object value, DateTime expDate); 4 void AddCache(string key, object value); 5 object GetCache(string key); 6 T GetCache<T>(string key); 7 void SetCache(string key, object value, DateTime extDate); 8 void SetCache(string key, object value); 9 }
1 public class CacheHelper 2 { 3 public static ICacheWriter CacheWriter { get; set; } 4 5 static CacheHelper() 6 { 7 CacheWriter = new MemcacheWriter(); 8 } 9 public static void AddCache(string key, object value, DateTime expDate) 10 { 11 CacheWriter.AddCache(key, value, expDate); 12 } 13 public static void AddCache(string key, object value) 14 { 15 CacheWriter.AddCache(key, value); 16 } 17 18 public static object GetCache(string key) 19 { 20 return CacheWriter.GetCache(key); 21 } 22 23 public static void SetCache(string key, object value, DateTime extTime) 24 { 25 CacheWriter.SetCache(key, value, extTime); 26 } 27 28 public static void SetCache(string key, object value) 29 { 30 CacheWriter.SetCache(key, value); 31 } 32 }
1 public class MemcacheWriter : ICacheWriter 2 { 3 private MemcachedClient memcachedClient; 4 public MemcacheWriter() 5 { 6 string strAppMemcachedServer = System.Configuration.ConfigurationManager.AppSettings["MemcachedServerList"]; 7 string[] servers = strAppMemcachedServer.Split(','); 8 9 //初始化池 10 SockIOPool pool = SockIOPool.GetInstance(); 11 pool.SetServers(servers); 12 pool.InitConnections = 3; 13 pool.MinConnections = 3; 14 pool.MaxConnections = 5; 15 pool.SocketConnectTimeout = 1000; 16 pool.SocketTimeout = 3000; 17 pool.MaintenanceSleep = 30; 18 pool.Failover = true; 19 pool.Nagle = false; 20 pool.Initialize(); 21 22 MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient(); 23 mc.EnableCompression = false; 24 25 memcachedClient = mc; 26 } 27 28 29 public void AddCache(string key, object value, DateTime expDate) 30 { 31 memcachedClient.Add(key, value, expDate); 32 } 33 34 public void AddCache(string key, object value) 35 { 36 memcachedClient.Add(key, value); 37 } 38 39 public object GetCache(string key) 40 { 41 return memcachedClient.Get(key); 42 } 43 44 public T GetCache<T>(string key) 45 { 46 return (T)memcachedClient.Get(key); 47 } 48 public void SetCache(string key, object value, DateTime extDate) 49 { 50 memcachedClient.Set(key, value, extDate); 51 } 52 53 public void SetCache(string key, object value) 54 { 55 memcachedClient.Set(key, value); 56 } 57 }
1 public static class Utils 2 { 3 #region GetSHA1(string str) # 4 public static string GetSHA1(string str) 5 { 6 byte[] cleanBytes = Encoding.Default.GetBytes(str); 7 byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes); 8 return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); 9 } 10 #endregion 11 }
WebAPIService
1 #region 获取授权的TOKEN 2 /// <summary> 3 /// 获取授权的TOKEN 4 /// </summary> 5 /// <param name="userId">当前用户ID</param> 6 /// <returns></returns> 7 [AcceptVerbs("GET")] 8 public IHttpActionResult GetTokenResult() 9 { 10 long timeStamp = DateTime.Now.ConvertTimestamp(); 11 try 12 { 13 string token = Guid.NewGuid().ToString("N"); 14 _msg = new Message() 15 { 16 retcode = 200, 17 resTime = timeStamp, 18 toKen = token, 19 retmsg = "成功" 20 }; 21 //缓存到memcached 用户的TOKEN 失效时间是一分钟 22 CacheHelper.SetCache(token, token, DateTime.Now.AddMinutes(1)); 23 var toek = CacheHelper.GetCache(token); 24 } 25 catch 26 { 27 _msg = new Message() { retcode = -1, resTime = timeStamp, retmsg = "获取TOKEN失败!" }; 28 } 29 return Json(_msg); 30 } 31 #endregion 32 33 private bool IsValideLogin(UserLoginInfo userLoginInfo, out Message msg) 34 { 35 msg = null; 36 bool result = false; 37 long timeStamp = DateTime.Now.ConvertTimestamp(); 38 try 39 { 40 //采用DES+KEY 对数据加密 41 42 //从memcached 获取用户的授权令牌进行匹配,如果匹配上说明身份已经验证过,无需要二次验证损耗性能 43 var _sign = CacheHelper.GetCache(userLoginInfo.userId.ToString(CultureInfo.InvariantCulture)); 44 if (_sign != null && !string.IsNullOrEmpty(_sign.ToString())) 45 { 46 if (!string.IsNullOrEmpty(userLoginInfo.SIGN) && 47 userLoginInfo.SIGN.Equals(_sign.ToString(), StringComparison.OrdinalIgnoreCase)) 48 { 49 result = true; 50 } 51 } 52 53 //1.从memcached 读取用户的token 检查token 是否授权 54 var _token = CacheHelper.GetCache(userLoginInfo.TOKEN); 55 if (_token != null && !string.IsNullOrEmpty(_token.ToString())) 56 { 57 //模拟读取数据库已配置的key密钥 58 string key = "cvuUldfieEULqfjdi92k1-lsdf#*ksdf2jd@ld0"; 59 60 string userId = userLoginInfo.userId.ToString(); 61 string timeStamps = userLoginInfo.timeStamp.ToString(); 62 63 //3.SHA1加密匹配参数是否正确 64 string[] temps = { userId, timeStamps, key, _token.ToString() }; 65 Array.Sort(temps); 66 string sign = Utils.GetSHA1(string.Join("", temps)); 67 if (!string.IsNullOrEmpty(userLoginInfo.SIGN) && 68 sign.Equals(userLoginInfo.SIGN, StringComparison.OrdinalIgnoreCase)) 69 { 70 result = true; 71 //设置到memcache 设置有效期为1天时间 授权的临时令牌 分发给用户 72 //这里可以使用DES加密过的串分发给用户 DES+KEY 73 CacheHelper.SetCache(userLoginInfo.userId.ToString(CultureInfo.InvariantCulture), sign, DateTime.Now.AddDays(1)); 74 } 75 else 76 { 77 msg = new Message() { resTime = timeStamp, retcode = -2000, retmsg = "身份验证失败,非法请求!" }; 78 return result = false; 79 } 80 } 81 else 82 { 83 msg = new Message() { resTime = timeStamp, retcode = -3000, retmsg = "非法请求,未授权的TOKEN" }; 84 return result = false; 85 } 86 } 87 catch 88 { 89 msg = new Message() { resTime = timeStamp, retcode = 500, retmsg = "身份验证服务出错!" }; 90 return result = false; 91 } 92 return result; 93 }
WebAPIClient
1 RestClient client = new RestClient("http://192.168.64.231:32768"); 2 3 UserLoginInfo User = new UserLoginInfo(); 4 5 #region Get 方式请求列表 6 string str = client.Get("api/values"); 7 Message msg = JsonConvert.DeserializeObject<Message>(str); 8 9 string userId = "10000"; 10 string timeStamp = msg.resTime.ToString(); 11 string key = "cvuUldfieEULqfjdi92k1-lsdf#*ksdf2jd@ld0"; 12 string[] temps = { userId, timeStamp, key, msg.toKen }; 13 Array.Sort(temps); 14 string sign = Utils.GetSHA1(string.Join("", temps)); 15 16 //1.获取授权的TOKEN 17 User.userId = userId; 18 User.TOKEN = msg.toKen; 19 User.SIGN = sign; 20 User.timeStamp = msg.resTime.ToString(); 21 22 Console.WriteLine(str); 23 #endregion 24 25 26 #region Post 方式 添加数据 27 28 string postUri = "api/values/1"; 29 30 //string userJson = @"{""Id"":123,""Age"":12,""UserInfo"":""111""}"; 31 string userJson = JsonConvert.SerializeObject(User); 32 string postResponse = client.Post(userJson, postUri); 33 34 Console.WriteLine(postResponse); 35 #endregion 36 37 38 Console.ReadKey();