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:
- AgreementRef
- AS4From
- AS4To
- ConversationId
- EDIData
- Errors
- IncomingReceipt
- MessageId
- MessageProperties
- MPC
- Service
- ServiceAction
- ServiceType
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 receiptReceiving 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 receiptAt 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.
AgreementRef | The agreement reference. |
AS4From | Defines information about the originating party. |
AS4To | Defines information about the responding party. |
AsyncReceiptInfoDir | A directory to hold information used for asynchronous receipt verification. |
Certificate | The certificate with private key used for decryption. |
ConversationId | The Conversation Id of the message. |
EDIData | The EDI data. |
EncryptionAlgorithm | The algorithm used to encrypt the EDI data. |
Errors | A collection of errors. |
IncomingDirectory | The directory to which incoming files are saved. |
IncomingReceipt | The receipt included with the request. |
LogDirectory | The path to a directory for logging. |
LogFile | The log file written. |
MessageId | The unique Id of the message. |
MessageProperties | A collection of message properties. |
MPC | The MPC (Message Partition Channel) from which files are requested. |
OriginalSOAPMessage | The original SOAP message used to verify the receipt. |
OriginalSOAPMessageId | The original SOAP message Id used to verify the receipt. |
Profile | The AS4 profile. |
Receipt | The receipt of a message. |
ReceiptReplyMode | The expected receipt reply mode. |
RecipientCerts | The public certificate used to encrypt files when sending. |
RefToMessageId | Specifies the RefToMessageId in the message. |
Request | The HTTP request to be processed. |
RequestHeaders | The HTTP headers in the AS4 request. |
RequestHeadersString | The HTTP headers in the AS4 request. |
Service | The service which acts on the message. |
ServiceAction | The action within a service that acts on the message. |
ServiceType | The type of service. |
SignatureAlgorithm | Signature algorithm to be used in the message. |
SignerCert | The public certificate used to verify signatures. |
SigningCert | The 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.
Config | Sets or retrieves a configuration setting. |
DoEvents | Processes events from the internal message queue. |
Interrupt | Interrupt the current method. |
ParseRequest | Parses and processes the message. |
ReadRequest | Reads the AS4 request. |
Reset | Resets the state of the control. |
SendAckResponse | Sends an acknowledgement of the request only. |
SendResponse | This method sends the response over the current HTTP context. |
SetRequestStream | Sets the stream from which the component will read the AS4 request. |
VerifyReceipt | Verifies 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.
Error | Information about errors during data delivery. |
Log | Fired with log information while processing a message. |
RecipientInfo | Fired for each recipient certificate of the encrypted message. |
SignerCertInfo | Fired during verification of the signed message. |
TokenAuthentication | Fired 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.
AgreementRefPMode | AgreementRef PMode of message. |
AgreementRefType | The type of AgreementRef. |
AllowWarnings | Whether warnings are interpreted as fatal errors. |
AttachXMLFiles | Whether to send XML files as attachments or within the SOAP body. |
CloseStreamAfterProcessing | Whether to close the input or output stream after processing. |
CompressXMLPayloads | Whether to compress XML data. |
ContentTransferEncoding | The content encoding of the payload data. |
DetectDuplicates | Whether to detect duplicate messages when receiving. |
EBPrefix | Specifies the prefix to use for messaging. |
EDIDataPartId[i] | Specified the part Id at the given index. |
EncryptionSecurityTokenFormat | The format to use for the security token when encryption. |
FilenameProperty | Defines a part property to hold the filename. |
ForceSigningCert | Whether to force only the SigningCert to be used for signing. |
FromId[i] | The Id of the party specified by AS4From. |
FromIdCount | The number of Ids for the party specified by AS4From. |
FromIdType[i] | The Id type of the party specified by AS4From. |
IdRight | A custom Id for the right side of the MessageId. |
KeyEncryptionAlgorithm | The algorithm used to encrypt the key. |
LogLevel | The level of information to log. |
LogOptions | The information to be written to log files. |
MessageType | Indicates the type of message received. |
NormalizeIssuerSubject | Whether to normalize the certificate subject within the X509Data element. |
OAEPMGF1HashAlgorithm | The MGF1 hash algorithm used when encrypting a key. |
OAEPParams | The hex encoded OAEP parameters to be used when encrypting a key. |
OAEPRSAHashAlgorithm | The RSA hash algorithm used when encrypting a key. |
ReferenceHashAlgorithm | The hash algorithm used to has the data specified in the reference of a signature. |
RequireEncryption | Whether encryption is required when processing received messages. |
RequireSignature | Whether a signature is required when processing received messages. |
ResponseBody | The body for the AS4 response message. |
ResponseFile | A file from which to read the response. |
ResponseHeaders | The headers for the AS4 response message. |
ResponseToFile | Creates the AS4 response message on disk. |
ResponseToString | Creates the AS4 response message in memory. |
SignerCACert | The CA certificates that issued the signer certificate. |
SigningSecurityTokenFormat | The format to use for the security token when signing. |
TempPath | Where temporary files are optionally written. |
ToId[i] | The Id of the party specified by AS4To. |
ToIdCount | The number of Ids for the party specified by AS4To. |
ToIdType[i] | The Id type of the party specified by AS4To. |
TransformReceipt | Whether to canonicalize the received receipt. |
WriteLogFilesToEvent | Whether to log the contents of the LogFiles in the Log event. |
AcceptEncoding | Used to tell the server which types of content encodings the client supports. |
AllowHTTPCompression | This property enables HTTP compression for receiving data. |
AllowHTTPFallback | Whether HTTP/2 connections are permitted to fallback to HTTP/1.1. |
AllowNTLMFallback | Whether to allow fallback from Negotiate to NTLM when authenticating. |
Append | Whether to append data to LocalFile. |
Authorization | The Authorization string to be sent to the server. |
BytesTransferred | Contains the number of bytes transferred in the response data. |
ChunkSize | Specifies the chunk size in bytes when using chunked encoding. |
CompressHTTPRequest | Set to true to compress the body of a PUT or POST request. |
EncodeURL | If set to true the URL will be encoded by the component. |
FollowRedirects | Determines what happens when the server issues a redirect. |
GetOn302Redirect | If set to true the component will perform a GET on the new location. |
HTTP2HeadersWithoutIndexing | HTTP2 headers that should not update the dynamic header table with incremental indexing. |
HTTPVersion | The version of HTTP used by the component. |
IfModifiedSince | A date determining the maximum age of the desired document. |
KeepAlive | Determines whether the HTTP connection is closed after completion of the request. |
KerberosSPN | The Service Principal Name for the Kerberos Domain Controller. |
LogLevel | The level of detail that is logged. |
MaxHeaders | Instructs component to save the amount of headers specified that are returned by the server after a Header event has been fired. |
MaxHTTPCookies | Instructs component to save the amount of cookies specified that are returned by the server when a SetCookie event is fired. |
MaxRedirectAttempts | Limits the number of redirects that are followed in a request. |
NegotiatedHTTPVersion | The negotiated HTTP version. |
OtherHeaders | Other headers as determined by the user (optional). |
ProxyAuthorization | The authorization string to be sent to the proxy server. |
ProxyAuthScheme | The authorization scheme to be used for the proxy. |
ProxyPassword | A password if authentication is to be used for the proxy. |
ProxyPort | Port for the proxy server (default 80). |
ProxyServer | Name or IP address of a proxy server (optional). |
ProxyUser | A user name if authentication is to be used for the proxy. |
SentHeaders | The full set of headers as sent by the client. |
StatusLine | The first line of the last response from the server. |
TransferredData | The contents of the last response from the server. |
TransferredDataLimit | The maximum number of incoming bytes to be stored by the component. |
TransferredHeaders | The full set of headers as received from the server. |
TransferredRequest | The full request as sent by the client. |
UseChunkedEncoding | Enables or Disables HTTP chunked encoding for transfers. |
UseIDNs | Whether to encode hostnames to internationalized domain names. |
UsePlatformDeflate | Whether to use the platform implementation to decompress compressed responses. |
UsePlatformHTTPClient | Whether or not to use the platform HTTP client. |
UserAgent | Information about the user agent (browser). |
CloseStreamAfterTransfer | If true, the component will close the upload or download stream after the transfer. |
ConnectionTimeout | Sets a separate timeout value for establishing a connection. |
FirewallAutoDetect | Tells the component whether or not to automatically detect and use firewall system settings, if available. |
FirewallHost | Name or IP address of firewall (optional). |
FirewallListener | If true, the component binds to a SOCKS firewall as a server (IPPort only). |
FirewallPassword | Password to be used if authentication is to be used when connecting through the firewall. |
FirewallPort | The TCP port for the FirewallHost;. |
FirewallType | Determines the type of firewall to connect through. |
FirewallUser | A user name if authentication is to be used connecting through a firewall. |
KeepAliveInterval | The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received. |
KeepAliveTime | The inactivity time in milliseconds before a TCP keep-alive packet is sent. |
Linger | When set to True, connections are terminated gracefully. |
LingerTime | Time in seconds to have the connection linger. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The port in the local host where the component binds. |
MaxLineLength | The maximum amount of data to accumulate when no EOL is found. |
MaxTransferRate | The transfer rate limit in bytes per second. |
ProxyExceptionsList | A semicolon separated list of hosts and IPs to bypass when using a proxy. |
TCPKeepAlive | Determines whether or not the keep alive socket option is enabled. |
TcpNoDelay | Whether or not to delay when sending packets. |
UseIPv6 | Whether to use IPv6. |
UseNTLMv2 | Whether to use NTLM V2. |
CACertFilePaths | The paths to CA certificate files when using Mono on Unix/Linux. |
LogSSLPackets | Controls whether SSL packets are logged when using the internal security API. |
ReuseSSLSession | Determines if the SSL session is reused. |
SSLCACerts | A newline separated list of CA certificate to use during SSL client authentication. |
SSLCheckCRL | Whether to check the Certificate Revocation List for the server certificate. |
SSLCipherStrength | The minimum cipher strength used for bulk encryption. |
SSLEnabledCipherSuites | The cipher suite to be used in an SSL negotiation. |
SSLEnabledProtocols | Used to enable/disable the supported security protocols. |
SSLEnableRenegotiation | Whether the renegotiation_info SSL extension is supported. |
SSLIncludeCertChain | Whether the entire certificate chain is included in the SSLServerAuthentication event. |
SSLNegotiatedCipher | Returns the negotiated ciphersuite. |
SSLNegotiatedCipherStrength | Returns the negotiated ciphersuite strength. |
SSLNegotiatedCipherSuite | Returns the negotiated ciphersuite. |
SSLNegotiatedKeyExchange | Returns the negotiated key exchange algorithm. |
SSLNegotiatedKeyExchangeStrength | Returns the negotiated key exchange algorithm strength. |
SSLNegotiatedVersion | Returns the negotiated protocol version. |
SSLProvider | The name of the security provider to use. |
SSLSecurityFlags | Flags that control certificate verification. |
SSLServerCACerts | A newline separated list of CA certificate to use during SSL server certificate validation. |
TLS12SignatureAlgorithms | Defines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True. |
TLS12SupportedGroups | The supported groups for ECC. |
TLS13KeyShareGroups | The groups for which to pregenerate key shares. |
TLS13SignatureAlgorithms | The allowed certificate signature algorithms. |
TLS13SupportedGroups | The supported groups for (EC)DHE key exchange. |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |
BuildInfo | Information about the product's build. |
GUIAvailable | Tells the component whether or not a message loop is available for processing events. |
LicenseInfo | Information about the current license. |
UseInternalSecurityAPI | Tells the component whether or not to use the system security libraries or an internal implementation. |