فهرست منبع

MQTT Redis操作,及密码登录验证等

黄贺彬 5 سال پیش
والد
کامیت
8f55be8d9d
5فایلهای تغییر یافته به همراه134 افزوده شده و 56 حذف شده
  1. 57 19
      HiTeachCE/Controllers/LoginController.cs
  2. 1 1
      HiTeachCE/Program.cs
  3. 29 22
      HiTeachCE/Startup.cs
  4. 35 0
      HiTeachCE/appsettings.Development.json
  5. 12 14
      HiTeachCE/appsettings.json

+ 57 - 19
HiTeachCE/Controllers/LoginController.cs

@@ -149,8 +149,9 @@ namespace HiTeachCE.Controllers
         [Authorize]
         public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
         {
-            List<string> ClientId = //new List<string>() { "fb564dde14df423cafac2085936e3b96" };
-             GetLoginUser(JwtClaimTypes.ClientId);
+            List<string> ClientId =   GetLoginUser(JwtClaimTypes.ClientId);
+            List<string> Unionid =   GetLoginUser(JwtClaimTypes.Id);
+            List<string> Role = GetLoginUser(JwtClaimTypes.Role);
             JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
             Dictionary<string, object> dict;
             /**
@@ -166,7 +167,7 @@ namespace HiTeachCE.Controllers
             {
                 if (RedisHelper.Exists("group:" + groupNum))
                 {
-                    dict =  MqttInfo(ClientId, deviceId, groupNum);
+                    dict =  MqttInfo(ClientId, deviceId, groupNum, Unionid, Role);
                 }
                 else {
                     throw new BizException("教室不存在", 2);
@@ -180,38 +181,75 @@ namespace HiTeachCE.Controllers
             return builder.Data(dict).build();
         }
 
-        private static Dictionary<string, object> MqttInfo(List<string> ClientId,  string deviceId, string groupNum)
+        private static Dictionary<string, object> MqttInfo(List<string> ClientId,  string deviceId, string groupNum,List<string> Unionid,List<string> Role)
         {
+            string brokerHostName = BaseConfigModel.Configuration["brokerHostName"];
+            
             Dictionary<string, object> dict = new Dictionary<string, object>();
-            string password = "cdhabook.teammodel.cn/" + groupNum +"/"+ deviceId +"/"+ ClientId[0];
+            string password = brokerHostName + "/" + groupNum +"/"+ deviceId +"/"+ ClientId[0];
             //发给前端使用的
             string h1 = BCrypt.Net.BCrypt.HashPassword(password);
             //后端存储使用的
             string h2 = BCrypt.Net.BCrypt.HashPassword(h1);
             bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
             string uname = password;
-            Dictionary<string, string> connectInfo = new Dictionary<string, string>() {
-                        { "brokerHostName", "cdhabook.teammodel.cn" },
-                        { "brokerHostNameWSS", "wss://cdhabook.teammodel.cn/mqtt" },
-                        { "clientID", deviceId },
-                        //使用BCrypt加密
-                        { "password",h1 },
-                        { "username",uname }
-                    };
-            dynamic groupMember = new
+            Dictionary<string,string> connectInfo = new Dictionary<string, string>
             {
-                deviceId,
-                username = uname,
-                password = h2
+                { "brokerHostName", brokerHostName  },
+                { "brokerHostNameWSS", "wss://" +brokerHostName+"/mqtt"} ,
+                { "clientID", deviceId },
+                //使用BCrypt加密
+                { "password",h1} ,
+                { "username",uname}
             };
-            RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);
             Dictionary<string, string> subscribeTopic = BaseConfigModel.Configuration.GetSection("SubscribeTopic").Get<Dictionary<string, string>>();
             subscribeTopic["receiveMsg"] = subscribeTopic["receiveMsg"].Replace("{deviceId}", deviceId);
             Dictionary<string, string> publishTopic = BaseConfigModel.Configuration.GetSection("PublishTopic").Get<Dictionary<string, string>>();
             publishTopic["sendMsg"] = publishTopic["sendMsg"].Replace("{deviceId}", deviceId).Replace("{groupNum}", groupNum);
             dict.Add("mqtt", new Dictionary<string, object>() { { "connectInfo", connectInfo },{ "publishTopic", publishTopic },{ "subscribeTopic", subscribeTopic } });
+            List<string> topic = new List<string>();
+            topic.AddRange(publishTopic.Values.ToList());
+            topic.AddRange(subscribeTopic.Values.ToList());
+            MQTTInfo mqtt = new MQTTInfo
+            {
+                brokerHostName = brokerHostName,
+                brokerHostNameWSS = "wss://" + brokerHostName + "/mqtt",
+                clientID = deviceId,
+                //使用BCrypt加密
+                password = h2,
+                username = uname,
+                topic=topic
+            };
+            var groupMember = new MQTTMember
+            {
+                clientId= ClientId[0],
+                deviceId=deviceId,
+                unionid=Unionid[0],
+                role=Role[0],
+                groupNum=groupNum
+            };
+            RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);
+            RedisHelper.HSet("mqtt:" + deviceId, deviceId, mqtt);
+            RedisHelper.Expire("mqtt:" + deviceId, deviceTTL);
             return dict;
         }
+        public class MQTTMember { 
+            public string groupNum { get; set; }
+            public string clientId { get; set; }
+            public string deviceId { get; set; }
+            public string unionid { get; set; }
+            public string role { get; set; }
+        }
+
+        public class MQTTInfo {
+            public string brokerHostName { get; set; }
+            public string brokerHostNameWSS { get; set; }
+            public string clientID { get; set; }
+            public string password { get; set; }
+            public string username { get; set; }
+            public List<string> topic { get;set;}
+
+        }
 
         /// <summary>
         /// 认证
@@ -415,7 +453,7 @@ namespace HiTeachCE.Controllers
                     {
                         request.@params.user.id = Guid.NewGuid().ToString();
                         request.@params.user.unionid = Guid.NewGuid().ToString("N");
-                        request.@params.user.unionid = "86";
+                        request.@params.user.areaCode = "86";
                         if (request.@params.user.password == null)
                         {
                             request.@params.user.password = "";

+ 1 - 1
HiTeachCE/Program.cs

@@ -19,7 +19,7 @@ namespace HiTeachCE
         {
             string h1= BCrypt.Net.BCrypt.HashPassword("https://sokrates.habookaclass.biz");
             string h2=  BCrypt.Net.BCrypt.HashPassword(h1);
-            bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
+            bool validPassword = BCrypt.Net.BCrypt.Verify("$2b$10$xbtKVxfp4aVNggRPby.XkukL14d0UErWeHGv6OeeIFll4e5g1hHue", "$2b$10$FT/BM7W/hiATZqyX1f0sleqtLMD7.yrd.bJtaanVwqsPumEyByh0W");
             CreateHostBuilder(args).Build().Run();
         }
 

+ 29 - 22
HiTeachCE/Startup.cs

@@ -25,6 +25,7 @@ using SqlSugar;
 using TEAMModelOS.SDK.Context.Configuration;
 using TEAMModelOS.SDK.Context.Filter;
 using TEAMModelOS.SDK.Extension.JwtAuth;
+using static HiTeachCE.Controllers.LoginController;
 
 namespace HiTeachCE
 {
@@ -80,28 +81,34 @@ namespace HiTeachCE
                 builder.WithDefaultEndpointPort(3000);
                 builder.WithConnectionValidator(c =>
                 {
-                   //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
-                   //  var serprovider = services.BuildServiceProvider();
-
-                   //  _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
-
-                   //if (c.ClientId.Length < 5)
-                   //{
-                   //    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
-                   //    return;
-                   //}
-
-                   //if (c.Username != "admin")
-                   //{
-                   //    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
-                   //    return;
-                   //}
-
-                   //if (c.Password != "public")
-                   //{
-                   //    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
-                   //    return;
-                   //}
+                    //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
+                    //  var serprovider = services.BuildServiceProvider();
+
+                    //  _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
+
+                    //if (c.ClientId.Length < 5)
+                    //{
+                    //    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
+                    //    return;
+                    //}
+                    MQTTInfo info= RedisHelper.HGet<MQTTInfo>("mqtt:"+c.ClientId, c.ClientId);
+                    if (info != null)
+                    {
+                        if (c.Username != info.username)
+                        {
+                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            return;
+                        }
+                        if (BCrypt.Net.BCrypt.Verify(c.Username , info.username))
+                        {
+                            c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            return;
+                        }
+                    }
+                    else {
+                        c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
+                        return;
+                    }
                    c.ReasonCode = MqttConnectReasonCode.Success;
                 })
                 .WithApplicationMessageInterceptor(context =>

+ 35 - 0
HiTeachCE/appsettings.Development.json

@@ -5,5 +5,40 @@
       "Microsoft": "Warning",
       "Microsoft.Hosting.Lifetime": "Information"
     }
+  },
+  "brokerHostName": "localhost:4001",
+  "DBConnection": {
+    "MySqlConnectionString": "server=106.12.23.251;database=HiTeachCE;port=3306;uid=root;pwd=teammodelabc123;charset='utf8mb4';SslMode=None"
+  },
+  "Redis": {
+    "ConnectionString": "106.12.23.251:6379,password=habook,ssl=false,abortConnect=False,defaultDatabase=11,writeBuffer=10240,poolsize=50,prefix=HiTeachCE:"
+  },
+  "JwtSetting": {
+    "Issuer": "HaBook", //签发者
+    "Audience": "HiTeachCE",
+    "JwtClient": [
+      {
+        "Name": "WebApp",
+        "Project": "HiTeachCE",
+        "Exp": 86400
+      }
+    ]
+  },
+  "JPush": {
+    "Push": "https://api.sms.jpush.cn/v1/codes",
+    "Valid": "https://api.sms.jpush.cn/v1/codes/{msg_id}/valid",
+    "AppKey": "ff01c4a2c87ffcda5268f010",
+    "Secret": "a4a19a5c556eeae3cffa5242"
+  },
+  "PublishTopic": {
+    "getTwin": "$iothub/twin/GET/?$rid=0",
+    "patchTwin": "$iothub/twin/PATCH/properties/reported/?$rid=0",
+    "sendDirectMethod": "$iothub/methods/res/200/?$rid=",
+    "sendMsg": "devices/{deviceId}/messages/events/endpoint=coretopiciot&groupNum={groupNum}&deviceId={deviceId}"
+  },
+  "SubscribeTopic": {
+    "receiveMsg": "devices/{deviceId}/messages/devicebound/#",
+    "receiveDirectMethod": "$iothub/methods/POST/directMethod/#",
+    "receiveTwin": "$iothub/twin/res/#"
   }
 }

+ 12 - 14
HiTeachCE/appsettings.json

@@ -7,6 +7,7 @@
     }
   },
   "AllowedHosts": "*",
+  "brokerHostName": "cdhabook.teammodel.cn",
   "DBConnection": {
     "MySqlConnectionString": "server=106.12.23.251;database=HiTeachCE;port=3306;uid=root;pwd=teammodelabc123;charset='utf8mb4';SslMode=None"
   },
@@ -30,18 +31,15 @@
     "AppKey": "ff01c4a2c87ffcda5268f010",
     "Secret": "a4a19a5c556eeae3cffa5242"
   },
-  "PublishTopic": 
-    {
-      "getTwin": "$iothub/twin/GET/?$rid=0",
-      "patchTwin": "$iothub/twin/PATCH/properties/reported/?$rid=0",
-      "sendDirectMethod": "$iothub/methods/res/200/?$rid=",
-      "sendMsg": "devices/{deviceId}/messages/events/endpoint=coretopiciot&groupNum={groupNum}&deviceId={deviceId}"
-    }
-  ,
-  "SubscribeTopic": 
-    {
-      "receiveMsg": "devices/{deviceId}/messages/devicebound/#",
-      "receiveDirectMethod": "$iothub/methods/POST/directMethod/#",
-      "receiveTwin": "$iothub/twin/res/#"
-    }
+  "PublishTopic": {
+    "getTwin": "$iothub/twin/GET/?$rid=0",
+    "patchTwin": "$iothub/twin/PATCH/properties/reported/?$rid=0",
+    "sendDirectMethod": "$iothub/methods/res/200/?$rid=",
+    "sendMsg": "devices/{deviceId}/messages/events/endpoint=coretopiciot&groupNum={groupNum}&deviceId={deviceId}"
+  },
+  "SubscribeTopic": {
+    "receiveMsg": "devices/{deviceId}/messages/devicebound/#",
+    "receiveDirectMethod": "$iothub/methods/POST/directMethod/#",
+    "receiveTwin": "$iothub/twin/res/#"
+  }
 }