AS4Server Component

Properties   Methods   Events   Configuration Settings   Errors  

The AS4Server component implements an AS4 / ebHandler.

Syntax

nsoftware.IPWorksEDI.As4server

Remarks

The AS4Server component implements server-side processing of AS4 messages. It may be used to receive files form a client (push), respond to a client's request for files (pull), and also handles generating and verifying receipts.

The component is designed to be easily integrated into a HTTP server, such as ASP.NET, but may also be used outside of a web server. The examples below assume the component is used within an environment where there is an HTTP context.

To begin, when a request is received first call ReadRequest. This reads the AS4 request from the current HttpContext. Alternatively the request data may be passed directly to the component by specifying calling SetRequestStream. After calling ReadRequest the following properties may be checked:

The first step after calling ReadRequest is to determine if the client is sending files (push) or requesting files (pull). To determine this check the value of AgreementRef and MPC. For instance:

if (server.AgreementRef == "" && server.MPC != "")
{
  //The client is requesting files from the specified MPC
  //No other relevant properties are populated
}
else //AgreementRef is not empty, and MPC is empty
{
  //The client is sending files. AgreementRef is populated with the agreement reference.
  //AS4From, AS4To, ConversationId, etc are populated
}

Determining if the request contains an asynchronous receipt from a previous transmission may also be done at this time by checking the IncomingReceipt property's Content field. If it is populated a receipt is present. To verify the receipt set AsyncReceiptInfoDir to the directory where information about the message was originally stored and call VerifyReceipt. If the receipt is signed SignerCert must also be set. See the section below and also SendFiles for more details.

Once information about the request is determined the component may then be configured to respond appropriately depending on the operation.

Receiving Files and Sending a Receipt

When receiving files first check the AgreementRef, AS4From, and AS4To properties to determine who is sending the files and with what previously agreed upon configuration. Once this is known, if the request is signed and encrypted set Certificate to the decryption certificate and SignerCert to the public certificate used for signature verification. IncomingDirectory may optionally be set to automatically store the incoming files.

//Process incoming files and send a signed receipt

server.ReadRequest();

//Inspect values from the request in order to load appropriate certificates etc.
//Console.WriteLine(server.AgreementRef);
//Console.WriteLine(server.AS4From.Id);
//Console.WriteLine(server.AS4To.Id);)

server.IncomingDirectory = "..\\MyFiles";
 
//Our private certificate. Used to decrypt the incoming file
server.Certificate = new Certificate(CertStoreTypes.cstPFXFile, Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyB.pfx"), "password", "*");

//Partner's public certificate. Used to verify the signature on the incoming message and files.
server.SignerCert = new Certificate(Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyA.cer"));

server.ParseRequest();

server.ReceiptReplyMode = As4serverReceiptReplyModes.rrmSync;

//Our private certificate. Used to sign the receipt.
server.SigningCert = new Certificate(CertStoreTypes.cstPFXFile, Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyB.pfx"), "password", "*");

server.SendResponse(); //Sends the receipt
Receiving Files and Sending an Asynchronous Receipt

Receipts may be sent in the response (synchronous) or at a later time (asynchronous). If the agreement specifies that the receipt be sent asynchronously the following steps may be taken to send the receipt.

After calling ReadRequest the ReceiptReplyMode may be set to indicate the receipt will be returned asynchronously. After calling ParseRequest call SendAckResponse to send back a HTTP 200 OK to the client. The receipt may then be returned later.

To send an asynchronous receipt AS4Client may be used. This can be sent to the partner's web site, or bundled with a later response (depending on the agreement made between the parties). In the example below AS4Client is used to send the receipt to the other party's web site.


//Process incoming files and send an asynchronous receipt

server.ReadRequest();

//Inspect values from the request in order to load appropriate certificates etc.
//Console.WriteLine(server.AgreementRef);
//Console.WriteLine(server.AS4From.Id);
//Console.WriteLine(server.AS4To.Id);)

server.IncomingDirectory = "..\\MyFiles";
 
//Our private certificate. Used to decrypt the incoming file
server.Certificate = new Certificate(CertStoreTypes.cstPFXFile, Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyB.pfx"), "password", "*");

//Partner's public certificate. Used to verify the signature on the incoming message and files.
server.SignerCert = new Certificate(Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyA.cer"));

server.ParseRequest();

server.ReceiptReplyMode = As4serverReceiptReplyModes.rrmAsync;

//Our private certificate. Used to sign the receipt.
server.SigningCert = new Certificate(CertStoreTypes.cstPFXFile, Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyB.pfx"), "password", "*");

server.SendAckResponse(); //Sends an ack, but not the receipt
At this point Receipt is populated with the receipt to be sent. Store the Receipt's Content and RefToMessageId values for use when sending the receipt later. Sending a receipt can be done with AS4Client.


//Send an asynchronous receipt
client.URL = ""http://www.company.com:9090/msh"";
client.Receipt = new EBReceipt(server.Receipt.RefToMessageId, server.Receipt.Content);
client.ReceiptReplyMode = As4clientReceiptReplyModes.rrmAsync;
client.SendReceipt();

Sending Files

To process a request to send files first check the MPC property. This holds the Message Partition Channel (MPC) from which the client would like to receive files. Next, set AgreementRef, AS4From, AS4To. Check IncomingReceipt to determine if the request has a bundled receipt. If it does VerifyReceipt can be called to verify the receipt.

Note: If the client requests files from the default MPC then MPC may be empty. See MessageType for details.

If the client makes use of UsernameToken authentication the TokenAuthentication event will fire when processing the request.

To send files back to the client simply set EDIData to the files you wish to send. When SendResponse is called the files will be sent back to the client.


//Process a request to send files (pull)

//Holds information from the original send so that receipts can be verified later
server.AsyncReceiptInfoDir = Path.Combine(Request.PhysicalApplicationPath, "..\\temp\\ReceiptInfoDir")

server.Profile = As4serverProfiles.ebpfENTSOG;
server.ReadRequest();

//The receipt may be signed depending upon the AgreementRef
server.SignerCert = new Certificate(Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyA.cer"));

//If the request has a bundled receipt verify it first
if (!string.IsNullOrEmpty(server.IncomingReceipt.Content))
{
  server.VerifyReceipt();
}

//If the request is a pull request (MPC is set)
if (server.AgreementRef == "" && server.MPC != "")
{
  server.AgreementRef = "http://agreements.company.com/pull_files";
  server.AS4From.Id = "org:holodeckb2b:example:company:B";
  server.AS4From.Role = "Sender";

  server.AS4To.Id = "org:holodeckb2b:example:company:A";
  server.AS4To.Role = "Receiver";

  server.ReceiptReplyMode = As4serverReceiptReplyModes.rrmAsync;

  //Our private certificate. Used to sign the message and files.
  server.SigningCert = new Certificate(CertStoreTypes.cstPFXFile, Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyB.pfx"), "password", "*");

  //Partner's public certificate. Used to encrypt files. 
  server.RecipientCerts.Add(new Certificate(Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyA.cer")));

  EBData data = new EBData();
  data.EDIType = "text/xml";
  data.Data = "<test>Hello AS4 World!</test>";
  server.EDIData.Add(data);

  server.SendResponse();
}

Processing Receipts

Any incoming request may potentially include a receipt. The request may be a receipt by itself, or it may be bundled with another type of request (send/receive). When initially sending files AsyncReceiptInfoDir may be set to store data about the original message on disk for use when verifying the receipt. If this is not desired manually store the OriginalSOAPMessage and OriginalSOAPMessageId instead.

To detect if an incoming request contains a receipt simply check the IncomingReceipt property's Content field. If it is populated the request includes a receipt. Set AsyncReceiptInfoDir to the same location as when the file was originally sent. Or alternatively set OriginalSOAPMessage and OriginalSOAPMessageId properties to the original values.

If the receipt is signed set SignerCert to the public certificate which will be used to verify the signature. Lastly call VerifyReceipt. This will perform any signature verification and verify the receipt content as well, matching it to the original message values.


server.ReadRequest();

//The receipt may be signed depending upon the AgreementRef
server.SignerCert = new Certificate(Path.Combine(Request.PhysicalApplicationPath, "..\\files\\CompanyA.cer"));

//If the request contains a receipt verify it
if (!string.IsNullOrEmpty(server.IncomingReceipt.Content))
{
  server.VerifyReceipt();
}

Property List


The following is the full list of the properties of the component with short descriptions. Click on the links for further details.

AgreementRefThe agreement reference.
AS4FromDefines information about the originating party.
AS4ToDefines information about the responding party.
AsyncReceiptInfoDirA directory to hold information used for asynchronous receipt verification.
CertificateThe certificate with private key used for decryption.
ConversationIdThe Conversation Id of the message.
EDIDataThe EDI data.
EncryptionAlgorithmThe algorithm used to encrypt the EDI data.
ErrorsA collection of errors.
IncomingDirectoryThe directory to which incoming files are saved.
IncomingReceiptThe receipt included with the request.
LogDirectoryThe path to a directory for logging.
LogFileThe log file written.
MessageIdThe unique Id of the message.
MessagePropertiesA collection of message properties.
MPCThe MPC (Message Partition Channel) from which files are requested.
OriginalSOAPMessageThe original SOAP message used to verify the receipt.
OriginalSOAPMessageIdThe original SOAP message Id used to verify the receipt.
ProfileThe AS4 profile.
ReceiptThe receipt of a message.
ReceiptReplyModeThe expected receipt reply mode.
RecipientCertsThe public certificate used to encrypt files when sending.
RefToMessageIdSpecifies the RefToMessageId in the message.
RequestThe HTTP request to be processed.
RequestHeadersThe HTTP headers in the AS4 request.
RequestHeadersStringThe HTTP headers in the AS4 request.
ServiceThe service which acts on the message.
ServiceActionThe action within a service that acts on the message.
ServiceTypeThe type of service.
SignatureAlgorithmSignature algorithm to be used in the message.
SignerCertThe public certificate used to verify signatures.
SigningCertThe certificate with private key used to sign messages and files.

Method List


The following is the full list of the methods of the component with short descriptions. Click on the links for further details.

ConfigSets or retrieves a configuration setting.
DoEventsProcesses events from the internal message queue.
InterruptInterrupt the current method.
ParseRequestParses and processes the message.
ReadRequestReads the AS4 request.
ResetResets the state of the control.
SendAckResponseSends an acknowledgement of the request only.
SendResponseThis method sends the response over the current HTTP context.
SetRequestStreamSets the stream from which the component will read the AS4 request.
VerifyReceiptVerifies a received receipt.

Event List


The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.

ErrorInformation about errors during data delivery.
LogFired with log information while processing a message.
RecipientInfoFired for each recipient certificate of the encrypted message.
SignerCertInfoFired during verification of the signed message.
TokenAuthenticationFired when the client makes use of UsernameToken authentication.

Configuration Settings


The following is a list of configuration settings for the component with short descriptions. Click on the links for further details.

AgreementRefPModeAgreementRef PMode of message.
AgreementRefTypeThe type of AgreementRef.
AllowWarningsWhether warnings are interpreted as fatal errors.
AttachXMLFilesWhether to send XML files as attachments or within the SOAP body.
CloseStreamAfterProcessingWhether to close the input or output stream after processing.
CompressXMLPayloadsWhether to compress XML data.
ContentTransferEncodingThe content encoding of the payload data.
DetectDuplicatesWhether to detect duplicate messages when receiving.
EBPrefixSpecifies the prefix to use for messaging.
EDIDataPartId[i]Specified the part Id at the given index.
EncryptionSecurityTokenFormatThe format to use for the security token when encryption.
FilenamePropertyDefines a part property to hold the filename.
ForceSigningCertWhether to force only the SigningCert to be used for signing.
FromId[i]The Id of the party specified by AS4From.
FromIdCountThe number of Ids for the party specified by AS4From.
FromIdType[i]The Id type of the party specified by AS4From.
IdRightA custom Id for the right side of the MessageId.
KeyEncryptionAlgorithmThe algorithm used to encrypt the key.
LogLevelThe level of information to log.
LogOptionsThe information to be written to log files.
MessageTypeIndicates the type of message received.
NormalizeIssuerSubjectWhether to normalize the certificate subject within the X509Data element.
OAEPMGF1HashAlgorithmThe MGF1 hash algorithm used when encrypting a key.
OAEPParamsThe hex encoded OAEP parameters to be used when encrypting a key.
OAEPRSAHashAlgorithmThe RSA hash algorithm used when encrypting a key.
ReferenceHashAlgorithmThe hash algorithm used to has the data specified in the reference of a signature.
RequireEncryptionWhether encryption is required when processing received messages.
RequireSignatureWhether a signature is required when processing received messages.
ResponseBodyThe body for the AS4 response message.
ResponseFileA file from which to read the response.
ResponseHeadersThe headers for the AS4 response message.
ResponseToFileCreates the AS4 response message on disk.
ResponseToStringCreates the AS4 response message in memory.
SignerCACertThe CA certificates that issued the signer certificate.
SigningSecurityTokenFormatThe format to use for the security token when signing.
TempPathWhere temporary files are optionally written.
ToId[i]The Id of the party specified by AS4To.
ToIdCountThe number of Ids for the party specified by AS4To.
ToIdType[i]The Id type of the party specified by AS4To.
TransformReceiptWhether to canonicalize the received receipt.
WriteLogFilesToEventWhether to log the contents of the LogFiles in the Log event.
AcceptEncodingUsed to tell the server which types of content encodings the client supports.
AllowHTTPCompressionThis property enables HTTP compression for receiving data.
AllowHTTPFallbackWhether HTTP/2 connections are permitted to fallback to HTTP/1.1.
AllowNTLMFallbackWhether to allow fallback from Negotiate to NTLM when authenticating.
AppendWhether to append data to LocalFile.
AuthorizationThe Authorization string to be sent to the server.
BytesTransferredContains the number of bytes transferred in the response data.
ChunkSizeSpecifies the chunk size in bytes when using chunked encoding.
CompressHTTPRequestSet to true to compress the body of a PUT or POST request.
EncodeURLIf set to true the URL will be encoded by the component.
FollowRedirectsDetermines what happens when the server issues a redirect.
GetOn302RedirectIf set to true the component will perform a GET on the new location.
HTTP2HeadersWithoutIndexingHTTP2 headers that should not update the dynamic header table with incremental indexing.
HTTPVersionThe version of HTTP used by the component.
IfModifiedSinceA date determining the maximum age of the desired document.
KeepAliveDetermines whether the HTTP connection is closed after completion of the request.
KerberosSPNThe Service Principal Name for the Kerberos Domain Controller.
LogLevelThe level of detail that is logged.
MaxHeadersInstructs component to save the amount of headers specified that are returned by the server after a Header event has been fired.
MaxHTTPCookiesInstructs component to save the amount of cookies specified that are returned by the server when a SetCookie event is fired.
MaxRedirectAttemptsLimits the number of redirects that are followed in a request.
NegotiatedHTTPVersionThe negotiated HTTP version.
OtherHeadersOther headers as determined by the user (optional).
ProxyAuthorizationThe authorization string to be sent to the proxy server.
ProxyAuthSchemeThe authorization scheme to be used for the proxy.
ProxyPasswordA password if authentication is to be used for the proxy.
ProxyPortPort for the proxy server (default 80).
ProxyServerName or IP address of a proxy server (optional).
ProxyUserA user name if authentication is to be used for the proxy.
SentHeadersThe full set of headers as sent by the client.
StatusLineThe first line of the last response from the server.
TransferredDataThe contents of the last response from the server.
TransferredDataLimitThe maximum number of incoming bytes to be stored by the component.
TransferredHeadersThe full set of headers as received from the server.
TransferredRequestThe full request as sent by the client.
UseChunkedEncodingEnables or Disables HTTP chunked encoding for transfers.
UseIDNsWhether to encode hostnames to internationalized domain names.
UsePlatformDeflateWhether to use the platform implementation to decompress compressed responses.
UsePlatformHTTPClientWhether or not to use the platform HTTP client.
UserAgentInformation about the user agent (browser).
CloseStreamAfterTransferIf true, the component will close the upload or download stream after the transfer.
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the component whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallListenerIf true, the component binds to a SOCKS firewall as a server (IPPort only).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the component binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
UseNTLMv2Whether to use NTLM V2.
CACertFilePathsThe paths to CA certificate files when using Mono on Unix/Linux.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedVersionReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
GUIAvailableTells the component whether or not a message loop is available for processing events.
LicenseInfoInformation about the current license.
UseInternalSecurityAPITells the component whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks EDI 2020 .NET Edition - Version 20.0 [Build 8203]