You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by jf...@apache.org on 2020/03/11 16:15:45 UTC

[plc4x] 03/06: Added parsing for username / passwort + Basic Auth.

This is an automated email from the ASF dual-hosted git repository.

jfeinauer pushed a commit to branch rel/0.6
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 1906a6450009542c9ac3683c948f697fa2b26c73
Author: Julian Feinauer <j....@pragmaticminds.de>
AuthorDate: Tue Mar 10 13:33:37 2020 +0100

    Added parsing for username / passwort + Basic Auth.
---
 plc4j/drivers/opcua/pom.xml                        | 15 +++++------
 .../apache/plc4x/java/opcua/OpcuaPlcDriver.java    |  5 ++++
 .../opcua/connection/BaseOpcuaPlcConnection.java   | 11 ++++++++
 .../opcua/connection/OpcuaTcpPlcConnection.java    | 29 +++++++++++++++++++---
 4 files changed, 50 insertions(+), 10 deletions(-)

diff --git a/plc4j/drivers/opcua/pom.xml b/plc4j/drivers/opcua/pom.xml
index 43ef5ca..7150836 100644
--- a/plc4j/drivers/opcua/pom.xml
+++ b/plc4j/drivers/opcua/pom.xml
@@ -71,12 +71,12 @@
     </dependency>
 
 
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>osgi.cmpn</artifactId>
-      <version>6.0.0</version>
-      <scope>provided</scope>
-    </dependency>
+  <dependency>
+    <groupId>org.osgi</groupId>
+    <artifactId>osgi.cmpn</artifactId>
+    <version>6.0.0</version>
+    <scope>provided</scope>
+  </dependency>
 
     <dependency>
       <groupId>org.bouncycastle</groupId>
@@ -88,7 +88,8 @@
       <artifactId>bcpkix-jdk15on</artifactId>
       <version>${bouncycastle.version}</version>
     </dependency>
-  </dependencies>
+
+</dependencies>
 
 
 <!--
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
index 185de95..9f3de51 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
@@ -25,6 +25,8 @@ import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
 import org.apache.plc4x.java.opcua.connection.OpcuaConnectionFactory;
 import org.apache.plc4x.java.spi.PlcDriver;
 import org.osgi.service.component.annotations.Component;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -41,6 +43,7 @@ import java.util.regex.Pattern;
 @Component(service = PlcDriver.class, immediate = true)
 public class OpcuaPlcDriver implements PlcDriver {
 
+    private static final Logger logger = LoggerFactory.getLogger(OpcuaPlcDriver.class);
 
     public static final Pattern INET_ADDRESS_PATTERN = Pattern.compile("tcp://(?<host>[\\w.-]+)(:(?<port>\\d*))?");
     public static final Pattern OPCUA_URI_PARAM_PATTERN = Pattern.compile("(?<param>[(\\?|\\&)([^=]+)\\=([^&]+)]+)?"); //later used for regex filtering of the params
@@ -80,6 +83,8 @@ public class OpcuaPlcDriver implements PlcDriver {
         Integer port = StringUtils.isNotBlank(portString) ? Integer.parseInt(portString) : null;
         String params = matcher.group("params") != null ? matcher.group("params").substring(1) : null;
 
+        logger.info("Path parameters given {}", params);
+
         try {
             return opcuaConnectionFactory.opcuaTcpPlcConnectionOf(InetAddress.getByName(host), port, params, requestTimeout);
         } catch (UnknownHostException e) {
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/BaseOpcuaPlcConnection.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/BaseOpcuaPlcConnection.java
index a7a2d43..ac6fba4 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/BaseOpcuaPlcConnection.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/BaseOpcuaPlcConnection.java
@@ -36,6 +36,9 @@ public abstract class BaseOpcuaPlcConnection extends AbstractPlcConnection imple
 
     private static final Logger logger = LoggerFactory.getLogger(BaseOpcuaPlcConnection.class);
     protected boolean skipDiscovery = false;
+    protected String username = null;
+    protected String password = null;
+    protected String certFile;
 
     /**
      * @param params
@@ -52,6 +55,14 @@ public abstract class BaseOpcuaPlcConnection extends AbstractPlcConnection imple
                         case "discovery":
                             skipDiscovery = !Boolean.valueOf(paramValue);
                             break;
+                        case "username":
+                            username = paramValue;
+                            break;
+                        case "password":
+                            password = paramValue;
+                            break;
+                        case "certFile":
+                            certFile = paramValue;
                         default:
                             logger.debug("Unknown parameter {} with value {}", paramName, paramValue);
                     }
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/OpcuaTcpPlcConnection.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/OpcuaTcpPlcConnection.java
index 1e9c603..76db3c0 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/OpcuaTcpPlcConnection.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/connection/OpcuaTcpPlcConnection.java
@@ -22,6 +22,7 @@ package org.apache.plc4x.java.opcua.connection;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
+import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
 import org.apache.plc4x.java.api.messages.*;
 import org.apache.plc4x.java.api.model.PlcConsumerRegistration;
 import org.apache.plc4x.java.api.model.PlcField;
@@ -36,6 +37,8 @@ import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
 import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
 import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
 import org.eclipse.milo.opcua.sdk.client.api.identity.IdentityProvider;
+import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
+import org.eclipse.milo.opcua.sdk.client.api.identity.X509IdentityProvider;
 import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem;
 import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
 import org.eclipse.milo.opcua.stack.client.DiscoveryClient;
@@ -49,15 +52,18 @@ import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
 import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
 import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
 import org.eclipse.milo.opcua.stack.core.types.structured.*;
+import org.eclipse.milo.opcua.stack.core.util.CertificateUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.File;
 import java.io.IOException;
 import java.math.BigInteger;
 import java.net.InetAddress;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.security.cert.X509Certificate;
 import java.time.Duration;
 import java.util.*;
 import java.util.concurrent.CompletableFuture;
@@ -171,7 +177,7 @@ public class OpcuaTcpPlcConnection extends BaseOpcuaPlcConnection {
         EndpointDescription endpoint = null;
 
         try {
-            endpoints = DiscoveryClient.getEndpoints(getEndpointUrl(address, port, getSubPathOfParams(params))).get();
+            endpoints = DiscoveryClient.getEndpoints(getEndpointUrl(address, port, getSubPathOfParams(params) == null ? "" : getSubPathOfParams(params))).get();
             //TODO Exception should be handeled better when the Discovery-API of Milo is stable
         } catch (Exception ex) {
             logger.info("Failed to discover Endpoint with enabled discovery. If the endpoint does not allow a correct discovery disable this option with the nDiscovery=true option. Failed Endpoint: {}", getEndpointUrl(address, port, params));
@@ -288,7 +294,7 @@ public class OpcuaTcpPlcConnection extends BaseOpcuaPlcConnection {
             throw new PlcConnectionException("The given input values are a not valid OPC UA connection configuration [CONFIG]: " + message);
         } catch (InterruptedException | ExecutionException e) {
             isConnected = false;
-            throw new PlcConnectionException("Error while creation of the connection because of : " + e.getMessage());
+            throw new PlcConnectionException("Error while creation of the connection because of : " + e.getMessage(), e);
         }
     }
 
@@ -543,7 +549,24 @@ public class OpcuaTcpPlcConnection extends BaseOpcuaPlcConnection {
     }
 
     private IdentityProvider getIdentityProvider() {
-        return new AnonymousProvider();
+        if (this.username != null) {
+            if (this.password == null) {
+                throw new PlcRuntimeException("Username given, but no password. Please Add password by providing &password=");
+            }
+            logger.info("Username {} is given and password {}, using Basic Auth now", this.username, this.password);
+            return new UsernameProvider(this.username, this.password);
+//        } else if (this.certFile != null) {
+//            logger.info("Using Certificate Path {}", this.certFile);
+//            try {
+//                final X509Certificate x509Certificate = CertificateUtil.decodeCertificate(Files.readAllBytes(new File(this.certFile).toPath()));
+//                return new X509IdentityProvider(x509Certificate);
+//            } catch (UaException | IOException e) {
+//                throw new PlcRuntimeException("Unable to load or decode Cert with path " + this.certFile);
+//            }
+        } else {
+            logger.info("No username / password is given, using anonymous access");
+            return new AnonymousProvider();
+        }
     }
 
     private static String getSubPathOfParams(String params){