轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
一起源码网 门户 终极进阶 查看主题

微信小程序登录数据解密以及状态维持

发布者: jiangtao | 发布时间: 2018-5-24 01:55| 查看数: 4613| 评论数: 1|帖子模式

说明:本文没有找到原文地址 
学习过小程序的朋友应该知道,在小程序中是不支持cookie的,借助小程序中的缓存我们也可以存储一些信息,但是对于一些比较重要的信息,我们需要通过登录状态维持来保存,同时,为了安全起见,用户的敏感信息,也是需要加密在网络上传输的。

前台,service。封装了http请求,同时封装了getSession(通过code获取服务器生成的session)、getUserInfo(获取用户信息)、getDecryptionData(解密数据)

  1. //service.js
  2. //封装了http服务,getUserInfo,提供回调函数
  3. var recourse = {
  4. doMain: ""
  5. }
  6. module.exports = {
  7. //Http Get
  8. requestGet: function (url, data, cb) {
  9. wx.request({
  10. url: recourse.doMain + url,
  11. data: data,
  12. method: 'GET',
  13. header: {},
  14. success: function (res) {
  15. cb(res, true)
  16. },
  17. fail: function () {
  18. cb(data, false)
  19. }
  20. })
  21. },
  22. //Http POST
  23. requestPost: function (url, data, cb) {
  24. wx.request({
  25. url: recourse.doMain + url,
  26. data: data,
  27. method: 'POST',
  28. header: {},
  29. success: function (res) {
  30. cb(res, true)
  31. },
  32. fail: function () {
  33. cb(data, false)
  34. }
  35. })
  36. },
  37. //获取第三方sessionId
  38. getSession: function (code, cb) {
  39. wx.request({
  40. url: recourse.doMain + 'SmallRoutine/PostCode',
  41. data: { code: code },
  42. method: 'POST',
  43. success: function (res) {
  44. cb(res, true)
  45. },
  46. fail: function (res) {
  47. cb(res, false)
  48. }
  49. })
  50. },
  51. //获取用户信息
  52. getUserInfo: function (cb) {
  53. wx.getUserInfo({
  54. success: function (res) {
  55. cb(res, true)
  56. },
  57. fail: function (res) {
  58. cb(res, false)
  59. }
  60. })
  61. },
  62. //获取解密数据
  63. getDecryptionData: function (cb) {
  64. wx.request({
  65. url: recourse.doMain+'SmallRoutine/Decryption',
  66. data: {
  67. encryptedData: wx.getStorageSync('encryptedData'),
  68. iv: wx.getStorageSync('iv'),
  69. session: wx.getStorageSync('thirdSessionId'),
  70. },
  71. method: 'POST',
  72. success: function (res) {
  73. cb(res, true)
  74. },
  75. fail: function (res) {
  76. cb(res, false)
  77. }
  78. })
  79. }
  80. }

后台,根据code获取session,客户端用来保持登录状态

  1. [HttpPost]
  2. public ActionResult PostCode(string code)
  3. {
  4. try
  5. {
  6. if(!string.IsNullOrEmpty(code))
  7. {
  8. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}&secret={1}&js_code={2}&grant_type=authorization_code",appId,appSecret,code));
  9. request.Method = "GET";
  10. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  11. StreamReader sr = new StreamReader(response.GetResponseStream());
  12. string content = sr.ReadToEnd();
  13. if(response.StatusCode == HttpStatusCode.OK)
  14. {
  15. var successModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ValidateCodeSuccess>(content);
  16. if(null != successModel.session_key)
  17. {
  18. //session_key是微信服务器生成的针对用户数据加密签名的密钥,不应该传输到客户端
  19. var session_key = successModel.session_key;
  20. //3re_session用于服务器和小程序之间做登录状态校验
  21. var thirdSession = Guid.NewGuid().ToString().Replace("-","");
  22. var now = DateTime.Now;
  23. //存到数据库或者redis缓存,这里一小时过期
  24. Service.AddLogin(new Domain.Login()
  25. {
  26. Code = code,
  27. Createime = now,
  28. OpenId = successModel.openid,
  29. OverdueTime = now.AddMinutes(60),
  30. SessionKey = successModel.session_key,
  31. SessionRd = thirdSession
  32. });
  33. return Json(new { success = true,session = thirdSession,openId = successModel.openid });
  34. }
  35. else
  36. {
  37. var errModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ValidateCodeFail>(content);
  38. return Json(new { success = false,msg = errModel.errcode + ":" + errModel.errmsg });
  39. }
  40. }
  41. else
  42. {
  43. var errModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ValidateCodeFail>(content);
  44. return Json(new { success = false,msg = errModel.errcode + ":" + errModel.errmsg });
  45. }
  46. }
  47. else
  48. {
  49. return Json(new { success = false,msg = "code不能为null" });
  50. }
  51. }
  52. catch(Exception e)
  53. {
  54. return Json(new { success = false });
  55. }
  56. }

解密敏感信息

  1. [HttpPost]
  2. public ActionResult Decryption(string encryptedData,string iv,string session)
  3. {
  4. try
  5. {
  6. var sessionKey = Service.GetSessionKey(session);
  7. if(!string.IsNullOrEmpty(sessionKey))
  8. {
  9. var str = AESDecrypt(encryptedData,sessionKey,iv);
  10. var data = Newtonsoft.Json.JsonConvert.DeserializeObject<EncryptedData>(str);
  11. if(null != data)
  12. {
  13. //服务器可以更新用户信息
  14. return Json(new { success = true,data = data });
  15. }
  16. }
  17. }
  18. catch(Exception e)
  19. {
  20. Service.AddLog("翻译错误:"+e.ToString());
  21. }
  22. return Json(new { success = false });
  23. }

AES解密

  1. public static string AESDecrypt(string encryptedData,string key,string iv)
  2. {
  3. if(string.IsNullOrEmpty(encryptedData)) return "";
  4. byte[] encryptedData2 = Convert.FromBase64String(encryptedData);
  5. System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
  6. {
  7. Key = Convert.FromBase64String(key),
  8. IV = Convert.FromBase64String(iv),
  9. Mode = System.Security.Cryptography.CipherMode.CBC,
  10. Padding = System.Security.Cryptography.PaddingMode.PKCS7
  11. };
  12. System.Security.Cryptography.ICryptoTransform ctf = rm.CreateDecryptor();
  13. Byte[] resultArray = ctf.TransformFinalBlock(encryptedData2,0,encryptedData2.Length);
  14. return Encoding.UTF8.GetString(resultArray);
  15. }

判断用户是否掉线

  1. [HttpPost]
  2. public ActionResult PostSession(string session)
  3. {
  4. if(!string.IsNullOrEmpty(session))
  5. {
  6. var loginInfo = Service.GetLoginInfo(session);
  7. if(null != loginInfo)
  8. {
  9. return Json(new { success = true,openId = loginInfo.OpenId });
  10. }
  11. else
  12. {
  13. return Json(new { success = false });
  14. }
  15. }
  16. return Json(new { success = false });
  17. }

前台index.js

  1. //index.js
  2. var app = getApp()
  3. Page({
  4. data: {
  5. userInfo: {},
  6. },
  7. onLoad: function () {
  8. var that = this
  9. app.getUserInfo(function (userInfo) {
  10. //更新数据
  11. that.setData({
  12. userInfo: userInfo
  13. })
  14. })
  15. }
  16. })

前台app.js

  1. var service = require('./service/service.js')
  2. var appConfig = {
  3. getUserInfo: function (cb) {
  4. var that = this
  5. if (that.globalData.userInfo) {
  6. //从缓存中用户信息
  7. } else {
  8. //wx api 登录
  9. wx.login({
  10. success: function (res) {
  11. console.log('登录成功 code 为:' + res.code);
  12. if (res.code) {
  13. service.getSession(res.code, function (res, success) {
  14. if (success) {
  15. console.log('通过 code 获取第三方服务器 session 成功, session 为:' + res.data.session);
  16. //缓存起来
  17. wx.setStorageSync('thirdSessionId', res.data.session);
  18. //wx api 获取用户信息
  19. service.getUserInfo(function (res, success) {
  20. if (success) {
  21. console.log('获取用户信息成功, 加密数据为:' + res.encryptedData);
  22. console.log('获取用户信息成功, 加密向量为:' + res.iv);
  23. //缓存敏感的用户信息,解密向量
  24. wx.setStorageSync('encryptedData', res.encryptedData);
  25. wx.setStorageSync('iv', res.iv);
  26. that.globalData.userInfo = res.userInfo;
  27. //解密数据
  28. service.getDecryptionData(function (res, success) {
  29. if (success) {
  30. console.log("解密数据成功");
  31. console.log(res.data.data);
  32. } else {
  33. console.log('解密数据失败');
  34. }
  35. })
  36. } else {
  37. console.log('获取用户信息失败')
  38. }
  39. });
  40. } else {
  41. console.log('通过 code 获取第三方服务器 session 失败');
  42. }
  43. });
  44. } else {
  45. console.log('登录失败:');
  46. }
  47. }
  48. })
  49. }
  50. },
  51. globalData: {
  52. userInfo: null
  53. }
  54. }
  55. App(appConfig)

运行输出:

最新评论

yzc3379 发表于 2022-6-18 17:42
免费网站源码平台

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表