UserAuthController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.Extensions.Logging;
  8. using Microsoft.Extensions.Options;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.IO;
  12. using Library;
  13. using LitJson;
  14. using MySystem.Models;
  15. using System.Net;
  16. namespace MySystem.Areas.Api.Controllers
  17. {
  18. [Area("Api")]
  19. [Route("Api/[controller]/[action]")]
  20. public class UserAuthController : BaseController
  21. {
  22. public UserAuthController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
  23. {
  24. }
  25. #region 小程序-获取secret
  26. public JsonResult GetSecret(string value)
  27. {
  28. value = DesDecrypt(value);
  29. JsonData data = JsonMapper.ToObject(value);
  30. string AppId = data["appId"].ToString(); //小程序AppId
  31. string AuthCode = data["authCode"].ToString(); //小程序授权码
  32. Projects pro = db.Projects.FirstOrDefault(m => m.AppId == AppId);
  33. if(pro == null)
  34. {
  35. return Json(new AppResultJson() { Status = "-1", Info = "appid不存在" });
  36. }
  37. pro = db.Projects.FirstOrDefault(m => m.AppId == AppId && m.AuthCode == AuthCode);
  38. if(pro == null)
  39. {
  40. return Json(new AppResultJson() { Status = "-1", Info = "授权码不正确" });
  41. }
  42. Dictionary<string, object> Obj = new Dictionary<string, object>();
  43. Obj.Add("appSecret", pro.AppSecret); //小程序密钥
  44. Obj.Add("appSalt", pro.AppIv); //小程序IV
  45. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  46. }
  47. #endregion
  48. #region 小程序-授权
  49. public JsonResult Auth(string value)
  50. {
  51. value = DesDecrypt(value);
  52. JsonData data = JsonMapper.ToObject(value);
  53. string AppId = data["appId"].ToString(); //小程序AppId
  54. string Code = data["code"].ToString(); //加密Code
  55. Projects pro = db.Projects.FirstOrDefault(m => m.AppId == AppId);
  56. if(pro == null)
  57. {
  58. return Json(new AppResultJson() { Status = "-1", Info = "appid不存在" });
  59. }
  60. string Data = AppDesDecrypt(Code, pro.AppSecret, pro.AppIv);
  61. if(string.IsNullOrEmpty(Data))
  62. {
  63. return Json(new AppResultJson() { Status = "-1", Info = "授权失败" });
  64. }
  65. string CheckAppId = Data.Substring(0, 16);
  66. if(CheckAppId != AppId)
  67. {
  68. return Json(new AppResultJson() { Status = "-1", Info = "授权失败" });
  69. }
  70. string UserId = Data.Substring(16);
  71. int PlateformUserId = int.Parse(UserId);
  72. string OpenId = "kxsmp_" + function.MD5_16(UserId + AppId);
  73. string Token = function.MD532(Guid.NewGuid().ToString() + "948576");
  74. UserForProject userFor = db.UserForProject.FirstOrDefault(m => m.PlateformUserId == PlateformUserId && m.AppId == AppId);
  75. if(userFor == null)
  76. {
  77. userFor = db.UserForProject.Add(new UserForProject()
  78. {
  79. CreateDate = DateTime.Now,
  80. UpdateDate = DateTime.Now.AddHours(1),
  81. PlateformUserId = PlateformUserId,
  82. AppId = AppId,
  83. OpenId = OpenId,
  84. Token = Token,
  85. }).Entity;
  86. }
  87. else
  88. {
  89. userFor.UpdateDate = DateTime.Now.AddHours(1);
  90. userFor.OpenId = OpenId;
  91. userFor.Token = Token;
  92. }
  93. db.SaveChanges();
  94. Dictionary<string, object> Obj = new Dictionary<string, object>();
  95. Obj.Add("appToken", Token); //小程序获取用户信息的Token
  96. Obj.Add("openId", OpenId); //小程序openId
  97. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  98. }
  99. #endregion
  100. #region 小程序-获取用户信息
  101. public JsonResult GetUserInfo(string value)
  102. {
  103. value = DesDecrypt(value);
  104. JsonData data = JsonMapper.ToObject(value);
  105. string AppToken = data["appToken"].ToString(); //小程序获取用户信息的Token
  106. string OpenId = data["openId"].ToString(); //小程序openId
  107. DateTime now = DateTime.Now;
  108. Dictionary<string, object> Obj = new Dictionary<string, object>();
  109. UserForProject userFor = db.UserForProject.FirstOrDefault(m => m.Token == AppToken && m.OpenId == OpenId && m.UpdateDate > now);
  110. if(userFor == null)
  111. {
  112. return Json(new AppResultJson() { Status = "-1", Info = "获取用户信息失败" });
  113. }
  114. PlateformModels.Users user = pdb.Users.FirstOrDefault(m => m.Id == userFor.PlateformUserId) ?? new PlateformModels.Users();
  115. Obj.Add("mobile", user.Mobile);
  116. Obj.Add("nickName", user.RealName); //昵称
  117. Obj.Add("headPhoto", SourceHost + user.HeadPhoto); //头像
  118. Obj.Add("makerCode", user.MakerCode);
  119. string province = "";
  120. string city = "";
  121. string district = "";
  122. if(!string.IsNullOrEmpty(user.Areas))
  123. {
  124. string[] AreaList = user.Areas.Split(',');
  125. if(AreaList.Length > 0) province = AreaList[0];
  126. if(AreaList.Length > 1) province = AreaList[1];
  127. if(AreaList.Length > 2) province = AreaList[2];
  128. }
  129. Obj.Add("province", province); //省
  130. Obj.Add("city", city); //市
  131. Obj.Add("district", district); //区
  132. Dictionary<string, string> tokens = GetToken(user.Id);
  133. Obj.Add("accessToken", tokens["access_token"]);
  134. Obj.Add("refreshToken", tokens["refresh_token"]);
  135. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  136. }
  137. public Dictionary<string, string> GetToken(int UserId)
  138. {
  139. Dictionary<string, string> obj = new Dictionary<string, string>();
  140. string access_token = "";
  141. string refresh_token = "";
  142. PlateformModels.WebCMSEntities db = new PlateformModels.WebCMSEntities();
  143. PlateformModels.Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new PlateformModels.Users();
  144. PlateformModels.UserMoveInfo userMove = db.UserMoveInfo.FirstOrDefault(m => m.UserId == UserId) ?? new PlateformModels.UserMoveInfo();
  145. string basic = "kxs_app:MxYh7A9Gkngp5YxWwKkuKlBGUaAIvpTn";
  146. basic = Convert.ToBase64String(Encoding.UTF8.GetBytes(basic));
  147. Dictionary<string, string> header = new Dictionary<string, string>();
  148. header.Add("Authorization", "Basic " + basic);
  149. string url = "https://apigateway.kexiaoshuang.com/v1/kxs/userServer/oauth2/token?scope=server&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer";
  150. Dictionary<string, string> req = new Dictionary<string, string>();
  151. req.Add("username", user.Mobile);
  152. req.Add("password", userMove.LoginPwd);
  153. string reqJson = Newtonsoft.Json.JsonConvert.SerializeObject(req);
  154. function.WriteLog("reqJson:" + reqJson, "拦截器日志");
  155. string jsonData = AesEncrypt(reqJson);
  156. function.WriteLog(str: "jsonData:" + jsonData, "拦截器日志");
  157. jsonData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData));
  158. string result = PostWebRequest(url, jsonData, header);
  159. function.WriteLog(str: "result:" + result, "拦截器日志");
  160. JsonData jsonObj = JsonMapper.ToObject(result);
  161. if(jsonObj["status"].ToString() == "1")
  162. {
  163. access_token = jsonObj["data"]["access_token"].ToString();
  164. refresh_token = jsonObj["data"]["refresh_token"].ToString();
  165. }
  166. obj.Add("access_token", access_token);
  167. obj.Add("refresh_token", refresh_token);
  168. return obj;
  169. }
  170. public string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
  171. {
  172. string ret = string.Empty;
  173. try
  174. {
  175. function.WriteLog(DateTime.Now.ToString(), "请求开店宝API日志");
  176. function.WriteLog(postUrl, "请求开店宝API日志");
  177. function.WriteLog(paramData, "请求开店宝API日志");
  178. byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
  179. // 设置提交的相关参数
  180. HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  181. System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
  182. request.Method = "POST";
  183. request.KeepAlive = false;
  184. request.AllowAutoRedirect = true;
  185. request.ContentType = "application/json";
  186. foreach (string key in headers.Keys)
  187. {
  188. request.Headers.Add(key, headers[key]);
  189. }
  190. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
  191. request.ContentLength = postData.Length;
  192. // 提交请求数据
  193. Stream outputStream = request.GetRequestStream();
  194. outputStream.Write(postData, 0, postData.Length);
  195. outputStream.Close();
  196. HttpWebResponse response;
  197. Stream responseStream;
  198. StreamReader reader;
  199. string srcString;
  200. response = request.GetResponse() as HttpWebResponse;
  201. responseStream = response.GetResponseStream();
  202. reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
  203. srcString = reader.ReadToEnd();
  204. ret = srcString; //返回值赋值
  205. reader.Close();
  206. function.WriteLog(srcString, "请求开店宝API日志");
  207. }
  208. catch (WebException ex)
  209. {
  210. HttpWebResponse response = (HttpWebResponse)ex.Response;
  211. Stream myResponseStream = response.GetResponseStream();
  212. //获取响应内容
  213. StreamReader myStreamReader = new StreamReader(myResponseStream);
  214. ret = myStreamReader.ReadToEnd();
  215. myResponseStream.Close();
  216. }
  217. catch (Exception ex)
  218. {
  219. ret = "fail";
  220. function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求开店宝API异常");
  221. }
  222. return ret;
  223. }
  224. public string AesEncrypt(string str)
  225. {
  226. if (string.IsNullOrEmpty(str)) return null;
  227. Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
  228. string key = "CBTU1dD4Kd5pyiGWTsI10jRQ3SvKusSV";
  229. string iv = "DYgjCEIMVrj2W9xN";
  230. System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
  231. {
  232. Key = Encoding.UTF8.GetBytes(key),
  233. IV = Encoding.UTF8.GetBytes(iv),
  234. Mode = System.Security.Cryptography.CipherMode.CBC,
  235. Padding = System.Security.Cryptography.PaddingMode.PKCS7
  236. };
  237. System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
  238. Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  239. return Convert.ToBase64String(resultArray, 0, resultArray.Length);
  240. }
  241. #endregion
  242. #region 3DES解密
  243. private string AppDesDecrypt(string encryptedText, string key, string iv)
  244. {
  245. string decryptedText = "";
  246. try
  247. {
  248. byte[] keyArray;
  249. byte[] ivArray;
  250. byte[] encryptedTextArray;
  251. byte[] decryptedTextArray;
  252. TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
  253. keyArray = UTF8Encoding.UTF8.GetBytes(key.Substring(0, 24));
  254. ivArray = UTF8Encoding.UTF8.GetBytes(iv);
  255. encryptedTextArray = Convert.FromBase64String(encryptedText);
  256. tripleDES.Key = keyArray;
  257. tripleDES.IV = ivArray;
  258. ICryptoTransform decryptor = tripleDES.CreateDecryptor(tripleDES.Key, tripleDES.IV);
  259. using (MemoryStream ms = new MemoryStream(encryptedTextArray))
  260. {
  261. using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
  262. {
  263. using (StreamReader sr = new StreamReader(cs))
  264. {
  265. decryptedTextArray = Encoding.UTF8.GetBytes(sr.ReadToEnd());
  266. }
  267. }
  268. }
  269. decryptedText = Encoding.UTF8.GetString(decryptedTextArray);
  270. }
  271. catch(Exception ex)
  272. {
  273. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "3DES解密异常");
  274. }
  275. return decryptedText;
  276. }
  277. #endregion
  278. }
  279. }