|
@@ -1,13 +1,14 @@
|
|
|
using Microsoft.AspNetCore.Builder;
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
+using Microsoft.Extensions.Configuration;
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
-using Newtonsoft.Json;
|
|
|
using System.Net.WebSockets;
|
|
|
+using System.Text;
|
|
|
|
|
|
namespace EVCB_OCPP.WSServer.Service.WsService;
|
|
|
|
|
|
-public static class AppExtention
|
|
|
+public static partial class AppExtention
|
|
|
{
|
|
|
public static void AddOcppWsServer(this IServiceCollection services)
|
|
|
{
|
|
@@ -15,7 +16,7 @@ public static class AppExtention
|
|
|
services.AddSingleton<OcppWebsocketService>();
|
|
|
}
|
|
|
|
|
|
- public static void MapOcppWsService(this WebApplication webApplication)
|
|
|
+ public static void UseOcppWsService(this WebApplication webApplication)
|
|
|
{
|
|
|
webApplication.UseWebSockets(new WebSocketOptions()
|
|
|
{
|
|
@@ -40,24 +41,31 @@ public static class AppExtention
|
|
|
public class OcppWebsocketService : WebsocketService<WsClientData>
|
|
|
{
|
|
|
public static List<string> protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0.1" };
|
|
|
+
|
|
|
+ private readonly IConfiguration configuration;
|
|
|
+ private readonly IMainDbService mainDbService;
|
|
|
private readonly ILogger<OcppWebsocketService> logger;
|
|
|
|
|
|
public OcppWebsocketService(
|
|
|
+ IConfiguration configuration,
|
|
|
IServiceProvider serviceProvider,
|
|
|
+ IMainDbService mainDbService,
|
|
|
ILogger<OcppWebsocketService> logger
|
|
|
) : base(serviceProvider)
|
|
|
{
|
|
|
+ this.configuration = configuration;
|
|
|
+ this.mainDbService = mainDbService;
|
|
|
this.logger = logger;
|
|
|
}
|
|
|
|
|
|
- internal override async ValueTask<string> AcceptWebSocketHandler(HttpContext context)
|
|
|
+ internal override async ValueTask<string> ValidateSupportedPortocol(HttpContext context)
|
|
|
{
|
|
|
- logger.LogInformation("{function}:{Path}/{SubProtocol}", nameof(AcceptWebSocketHandler), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
|
|
|
+ logger.LogInformation("{id} {function}:{Path}/{SubProtocol}", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
|
|
|
|
|
|
var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
|
|
|
if (string.IsNullOrEmpty(protocol))
|
|
|
{
|
|
|
- logger.LogInformation("{function}:{Path} Protocol Not Supported, Disconnecting", nameof(AcceptWebSocketHandler), context.Request.Path);
|
|
|
+ logger.LogInformation("{id} {function}:{Path} Protocol Not Supported, Disconnecting", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path);
|
|
|
|
|
|
using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
|
|
|
await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
|
|
@@ -66,6 +74,140 @@ public class OcppWebsocketService : WebsocketService<WsClientData>
|
|
|
return protocol;
|
|
|
}
|
|
|
|
|
|
+ internal override async ValueTask<bool> ValidateHandshake(HttpContext context, WsClientData session)
|
|
|
+ {
|
|
|
+ string authHeader = context?.Request?.Headers?.Authorization;
|
|
|
+
|
|
|
+ session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");
|
|
|
+
|
|
|
+ int securityProfile = 0;
|
|
|
+ string authorizationKey = string.Empty;
|
|
|
+ if (string.IsNullOrEmpty(session.Path))
|
|
|
+ {
|
|
|
+ //logger.Log();
|
|
|
+ logger.LogWarning("===========================================");
|
|
|
+ logger.LogWarning("{id} session.Path EMPTY", context.TraceIdentifier);
|
|
|
+ logger.LogWarning("===========================================");
|
|
|
+ }
|
|
|
+
|
|
|
+ string[] words = session.Path.ToString().Split('/');
|
|
|
+ session.ChargeBoxId = words.Last();
|
|
|
+ logger.LogDebug("{id} {0}:{1}", context.TraceIdentifier, session.ChargeBoxId, session.UriScheme);
|
|
|
+
|
|
|
+ foreach (var denyModel in GlobalConfig.DenyModelNames)
|
|
|
+ {
|
|
|
+ if (string.IsNullOrEmpty(denyModel))
|
|
|
+ {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (session.ChargeBoxId.StartsWith(denyModel))
|
|
|
+ {
|
|
|
+ context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
|
+
|
|
|
+ logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if (configuration["MaintainMode"] == "1")
|
|
|
+ {
|
|
|
+ session.ChargeBoxId = session.ChargeBoxId + "_2";
|
|
|
+ }
|
|
|
+
|
|
|
+ logger.LogInformation("{id} ValidateHandshake: {0}", context.TraceIdentifier, session.Path);
|
|
|
+ bool isExistedSN = false;
|
|
|
+ bool authorizated = false;
|
|
|
+
|
|
|
+ var info = await mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId);
|
|
|
+ //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
|
|
|
+ //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
|
|
|
+ //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
|
|
|
+ //session.MachineId = machine == null ? String.Empty : machine.Id;
|
|
|
+ //isExistedSN = machine == null ? false : true;
|
|
|
+ session.CustomerName = info.CustomerName;
|
|
|
+ session.CustomerId = info.CustomerId;
|
|
|
+ session.MachineId = info.MachineId;
|
|
|
+ isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
|
|
|
+
|
|
|
+ if (!isExistedSN)
|
|
|
+ {
|
|
|
+ context.Response.StatusCode = StatusCodes.Status404NotFound;
|
|
|
+ logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
|
|
|
+ // .Select(x => x.ConfigureSetting).FirstOrDefault();
|
|
|
+ var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
|
|
|
+ int.TryParse(configVaule, out securityProfile);
|
|
|
+
|
|
|
+ if (session.ISOCPP20)
|
|
|
+ {
|
|
|
+ // 1.6 server only support change server function
|
|
|
+ securityProfile = 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (securityProfile == 3 && session.UriScheme == "ws")
|
|
|
+ {
|
|
|
+ context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
|
+ logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (securityProfile == 1 || securityProfile == 2)
|
|
|
+ {
|
|
|
+ if (securityProfile == 2 && session.UriScheme == "ws")
|
|
|
+ {
|
|
|
+ authorizated = false;
|
|
|
+ }
|
|
|
+
|
|
|
+ //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
|
|
|
+ if (!string.IsNullOrEmpty(authHeader))
|
|
|
+ {
|
|
|
+ //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
|
|
|
+ // .Select(x => x.ConfigureSetting).FirstOrDefault();
|
|
|
+ authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);
|
|
|
+
|
|
|
+ if (session.ISOCPP20)
|
|
|
+ {
|
|
|
+ // 1.6 server only support change server function
|
|
|
+ securityProfile = 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ logger.LogInformation("{id} ***********Authorization ", context.TraceIdentifier);
|
|
|
+
|
|
|
+ if (!string.IsNullOrEmpty(authorizationKey))
|
|
|
+ {
|
|
|
+ //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
|
|
|
+ string base64Encoded = authHeader.Replace("Basic ", "");
|
|
|
+ byte[] data = Convert.FromBase64String(base64Encoded);
|
|
|
+ string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
|
|
|
+ logger.LogInformation("{id} ***********Authorization " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
|
|
|
+ if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
|
|
|
+ {
|
|
|
+ authorizated = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ authorizated = true;
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!authorizated)
|
|
|
+ {
|
|
|
+ context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
|
+ logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
|
|
|
{
|
|
|
int supportedProtocolIndex = supportedProtocols.Count - 1;
|