提交 015ed47f 编写于 作者: 麦壳饼's avatar 麦壳饼

修正和内置mqtt客户端相关的配置问题

上级 f4230c7f
......@@ -21,17 +21,17 @@ namespace IoTSharp
/// mqtt client settings
/// </summary>
public MqttClientSetting MqttClient { get; set; }
public string JwtAudience { get; set; }
}
public class MqttClientSetting
{
/// <summary>
/// built-in or IP、HostName
/// </summary>
public string MqttBroker { get; set; } = "built-in";
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
public int Port { get; set; } = 1883;
public string MqttBroker { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int Port { get; set; }
}
public class MqttBrokerSetting
{
......@@ -40,6 +40,6 @@ namespace IoTSharp
public bool EnableTls { get; set; } = false;
public string Certificate { get; set; }
public SslProtocols SslProtocol { get; set; } = SslProtocols.None;
public bool PersistRetainedMessages { get; internal set; }
public bool PersistRetainedMessages { get; set; }
}
}
......@@ -24,13 +24,12 @@ namespace IoTSharp
public static class MqttExtension
{
//static private IMqttServer _mqttServer;
public static void AddIoTSharpMqttServer(this IServiceCollection services, MqttBrokerSetting setting)
public static void AddIoTSharpMqttServer(this IServiceCollection services, MqttBrokerSetting broker)
{
services.AddMqttTcpServerAdapter();
services.AddHostedMqttServerEx(options =>
{
var broker = setting;
if (broker == null) broker = new MqttBrokerSetting();
options.WithDefaultEndpointPort(broker.Port).WithDefaultEndpoint();
if (broker.EnableTls)
{
......@@ -102,10 +101,10 @@ namespace IoTSharp
public static void AddMqttClient(this IServiceCollection services, MqttClientSetting setting)
{
if (setting == null) setting = new MqttClientSetting();
services.AddSingleton(options => new MQTTnet.MqttFactory().CreateMqttClient());
services.AddTransient(options => new MqttClientOptionsBuilder()
.WithClientId("buind-in")
.WithClientId(setting.MqttBroker)
.WithTcpServer((setting.MqttBroker == "built-in" || string.IsNullOrEmpty(setting.MqttBroker)) ? "127.0.0.1" : setting.MqttBroker, setting.Port)
.WithCredentials(setting.UserName, setting.Password)
.WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500)
......
......@@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet;
using MQTTnet.AspNetCoreEx;
using MQTTnet.Server;
......@@ -27,13 +28,16 @@ namespace IoTSharp.Handlers
readonly ILogger<MQTTServerHandler> _logger;
readonly ApplicationDbContext _dbContext;
readonly IMqttServerEx _serverEx;
readonly IServiceScope scope;
readonly MqttClientSetting _mcsetting;
public MQTTServerHandler(ILogger<MQTTServerHandler> logger, IServiceScopeFactory scopeFactor,IMqttServerEx serverEx, DiagnosticsService diagnosticsService,
RuntimeStatusHandler systemStatusService
RuntimeStatusHandler systemStatusService, IOptions <AppSettings> options
)
{
_mcsetting = options.Value.MqttClient;
_logger = logger;
_dbContext = scopeFactor.CreateScope().ServiceProvider.GetRequiredService<ApplicationDbContext>();
scope = scopeFactor.CreateScope();
_dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
_serverEx = serverEx;
InboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.inbound_rate");
OutboundCounter = diagnosticsService.CreateOperationsPerSecondCounter("mqtt.outbound_rate");
......@@ -337,11 +341,19 @@ namespace IoTSharp.Handlers
public static string MD5Sum(string text) => BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
internal void Server_ClientConnectionValidator(object sender, MqttServerClientConnectionValidatorEventArgs e)
{
var _dbContextcv = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
MqttConnectionValidatorContext obj = e.Context;
Uri uri = new Uri("mqtt://" + obj.Endpoint);
if (uri.IsLoopback && !string.IsNullOrEmpty(e.Context.ClientId) && e.Context.ClientId == _mcsetting.MqttBroker && !string.IsNullOrEmpty(e.Context.Username) && e.Context.Username == _mcsetting.UserName && e.Context.Password == _mcsetting.Password)
{
obj.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionAccepted;
}
else
{
_logger.LogInformation($"ClientId={obj.ClientId},Endpoint={obj.Endpoint},Username={obj.Username},Password={obj.Password},WillMessage={obj.WillMessage?.ConvertPayloadToString()}");
var mcr = _dbContext.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc => (mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username)
|| (mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.Username && mc.IdentityValue == obj.Password));
var mcr = _dbContextcv.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc =>
(mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username) ||
(mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.Username && mc.IdentityValue == obj.Password));
if (mcr != null)
{
try
......@@ -364,6 +376,7 @@ namespace IoTSharp.Handlers
_logger.LogInformation($"Bad username or password {obj.Username},connection {obj.Endpoint} refused");
}
}
}
public List<string> GetTopicImportUids()
{
......
......@@ -9,7 +9,7 @@ using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MQTTnet.AspNetCore;
namespace IoTSharp
{
public class Program
......
......@@ -40,10 +40,15 @@ namespace IoTSharp
public Startup(IConfiguration configuration)
{
Configuration = configuration;
AppSettings = Configuration.Get<AppSettings>();
settings = Configuration.Get<AppSettings>();
if (settings.MqttBroker == null) settings.MqttBroker = new MqttBrokerSetting();
if (settings.MqttClient == null) settings.MqttClient = new MqttClientSetting();
if (string.IsNullOrEmpty(settings.MqttClient.MqttBroker)) settings.MqttClient.MqttBroker = "built-in";
if (string.IsNullOrEmpty(settings.MqttClient.Password)) settings.MqttClient.Password = Guid.NewGuid().ToString();
if (string.IsNullOrEmpty(settings.MqttClient.UserName)) settings.MqttClient.UserName = Guid.NewGuid().ToString();
if (settings.MqttClient.Port == 0) settings.MqttClient.Port = 1883;
}
public AppSettings AppSettings { get; }
private AppSettings settings;
public IConfiguration Configuration { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container.
......@@ -62,11 +67,15 @@ namespace IoTSharp
{
configuration.RootPath = "ClientApp/dist";
});
services.Configure<AppSettings>(Configuration);
services.AddOptions();
services.Configure((Action<AppSettings>)(setting =>
{
Configuration.Bind(setting);
setting.MqttBroker = settings.MqttBroker;
setting.MqttClient = settings.MqttClient;
}));
services.AddLogging(loggingBuilder => loggingBuilder.AddConsole());
services.AddIoTSharpHub(Configuration);
// Enable the Gzip compression especially for Kestrel
services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
......@@ -80,7 +89,7 @@ namespace IoTSharp
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureJwtAuthentication(Configuration["JwtIssuer"], Configuration["JwtAudience"], Configuration["JwtKey"], TimeSpan.FromDays(Convert.ToInt32(Configuration["JwtExpireDays"])));
services.ConfigureJwtAuthentication(settings.JwtIssuer , settings.JwtAudience, settings.JwtKey, TimeSpan.FromDays(Convert.ToInt32(settings.JwtExpireDays)));
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
......@@ -95,8 +104,8 @@ namespace IoTSharp
configure.Description = description?.Description;
});
services.AddTransient<ApplicationDBInitializer>();
services.AddIoTSharpMqttServer(AppSettings.MqttBroker);
services.AddMqttClient(AppSettings.MqttClient);
services.AddIoTSharpMqttServer(settings.MqttBroker);
services.AddMqttClient(settings.MqttClient);
services.AddHostedService<CoAPService>();
services.AddHostedService<MQTTMessageService>();
services.AddSingleton<DiagnosticsService>();
......@@ -105,6 +114,7 @@ namespace IoTSharp
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册