-
Notifications
You must be signed in to change notification settings - Fork 0
CyberSource fixes #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
StanislavSmetaninSSM
wants to merge
10
commits into
main
Choose a base branch
from
ssm/28229-cybersource_fixes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f7d8f72
• Improve CyberSource provider compatibility
StanislavSmetaninSSM 7887fed
Code review fixes
StanislavSmetaninSSM 56147aa
Code review fixes
StanislavSmetaninSSM b90ffc7
Code review fixes
StanislavSmetaninSSM fe71b00
Code review fixes
StanislavSmetaninSSM b5a601d
Code review fixes.
StanislavSmetaninSSM e798127
Code review fixes
StanislavSmetaninSSM 66073fe
Code review fixes
StanislavSmetaninSSM 2f44819
Fixed bug in the GetCustomerLastName()
StanislavSmetaninSSM 6cbab95
Cosmetic fixes
StanislavSmetaninSSM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Net.Http; | ||
| using System.Security.Cryptography; | ||
| using System.Security.Cryptography.X509Certificates; | ||
| using System.Text; | ||
| using System.Text.Json; | ||
| using System.Text.RegularExpressions; | ||
|
|
||
| namespace Dynamicweb.Ecommerce.CheckoutHandlers.CyberSource.Helpers; | ||
|
|
||
| internal static class JwtAuthenticationHelper | ||
| { | ||
| /// <summary> | ||
| /// Generates a CyberSource REST API JWT v2 authentication token. | ||
| /// The required claims follow the current CyberSource REST JWT documentation and match the official | ||
| /// CyberSource .NET Standard authentication SDK output. | ||
| /// See https://developer.cybersource.com/docs/cybs/en-us/platform/developer/all/rest/rest-getting-started/restgs-jwt-message-intro/restgs-security-p12-intro.html. | ||
| /// </summary> | ||
| public static string GenerateCertificateToken(string merchantId, string certificateFile, string certificatePassword, HttpMethod method, string host, string resourcePath, string data) | ||
| { | ||
| try | ||
| { | ||
| string certificatePath = Helper.GetCertificateFilePath(certificateFile); | ||
| if (string.IsNullOrEmpty(certificatePath)) | ||
| throw new Exception("Certificate for REST API is not found"); | ||
|
|
||
| using X509Certificate2 x5Cert = new(certificatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet); | ||
| using RSA privateKey = x5Cert.GetRSAPrivateKey(); | ||
| if (privateKey is null) | ||
| throw new Exception("Certificate for REST API does not contain an RSA private key"); | ||
|
|
||
| Dictionary<string, object> header = GetHeaderClaims("RS256", GetCertificateKeyId(x5Cert)); | ||
| Dictionary<string, object> payload = GetPayloadClaims(merchantId, method, host, resourcePath, data); | ||
|
|
||
| return BuildJwt( | ||
| JsonSerializer.Serialize(header), | ||
| JsonSerializer.Serialize(payload), | ||
| privateKey); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| throw new Exception("Certificate JWT token creation failed", ex); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Generates a CyberSource REST API JWT v2 token signed with a REST Shared Secret key. | ||
| /// </summary> | ||
| /// <param name="merchantId">The CyberSource merchant ID used as the JWT issuer and merchant identifier.</param> | ||
| /// <param name="sharedSecretKeyId">The REST Shared Secret key ID from CyberSource Business Center Key Management.</param> | ||
| /// <param name="sharedSecret">The base64-encoded REST Shared Secret value from CyberSource Business Center Key Management.</param> | ||
| /// <param name="method">The HTTP method used for the CyberSource REST request.</param> | ||
| /// <param name="host">The CyberSource REST API host, for example <c>apitest.cybersource.com</c>.</param> | ||
| /// <param name="resourcePath">The REST resource path and query string being requested.</param> | ||
| /// <param name="data">The serialized request body. When present, its SHA-256 digest is included in the JWT payload.</param> | ||
| /// <returns>A signed JWT token suitable for the CyberSource REST API <c>Authorization: Bearer</c> header.</returns> | ||
| /// <exception cref="Exception"> | ||
| /// Thrown when required shared-secret settings are missing, the shared secret is not valid base64, or token signing fails. | ||
| /// </exception> | ||
| public static string GenerateSharedSecretToken(string merchantId, string sharedSecretKeyId, string sharedSecret, HttpMethod method, string host, string resourcePath, string data) | ||
| { | ||
| try | ||
| { | ||
| if (string.IsNullOrWhiteSpace(sharedSecretKeyId)) | ||
| throw new Exception("REST Shared Secret Key ID is not configured"); | ||
| if (string.IsNullOrWhiteSpace(sharedSecret)) | ||
| throw new Exception("REST Shared Secret is not configured"); | ||
|
|
||
| Dictionary<string, object> header = GetHeaderClaims("HS256", sharedSecretKeyId); | ||
| Dictionary<string, object> payload = GetPayloadClaims(merchantId, method, host, resourcePath, data); | ||
|
|
||
| return BuildJwt( | ||
| JsonSerializer.Serialize(header), | ||
| JsonSerializer.Serialize(payload), | ||
| Convert.FromBase64String(sharedSecret.Trim())); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| throw new Exception("Shared Secret JWT token creation failed", ex); | ||
| } | ||
| } | ||
|
|
||
| private static Dictionary<string, object> GetHeaderClaims(string algorithm, string keyId) => new() | ||
| { | ||
| ["alg"] = algorithm, | ||
| ["kid"] = keyId, | ||
| ["typ"] = "JWT" | ||
| }; | ||
|
|
||
| private static Dictionary<string, object> GetPayloadClaims(string merchantId, HttpMethod method, string host, string resourcePath, string data) | ||
| { | ||
| DateTimeOffset now = DateTimeOffset.UtcNow; | ||
| var payload = new Dictionary<string, object> | ||
| { | ||
| ["iat"] = now.ToUnixTimeSeconds(), | ||
| ["exp"] = now.AddMinutes(2).ToUnixTimeSeconds(), | ||
| ["request-method"] = method.Method.ToLowerInvariant(), | ||
| ["request-resource-path"] = resourcePath, | ||
| ["request-host"] = host, | ||
| ["iss"] = merchantId, | ||
| ["jti"] = Guid.NewGuid().ToString(), | ||
| ["v-c-jwt-version"] = "2", | ||
| ["v-c-merchant-id"] = merchantId | ||
| }; | ||
|
|
||
| if (!string.IsNullOrEmpty(data)) | ||
| { | ||
| payload["digest"] = GenerateDigest(data); | ||
| payload["digestAlgorithm"] = "SHA-256"; | ||
| } | ||
|
|
||
| return payload; | ||
| } | ||
|
|
||
| private static string BuildJwt(string header, string payload, RSA privateKey) | ||
| { | ||
| string signingInput = $"{Base64UrlEncode(header)}.{Base64UrlEncode(payload)}"; | ||
| byte[] signature = privateKey.SignData(Encoding.UTF8.GetBytes(signingInput), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); | ||
|
|
||
| return $"{signingInput}.{Base64UrlEncode(signature)}"; | ||
| } | ||
|
|
||
| private static string BuildJwt(string header, string payload, byte[] sharedSecret) | ||
| { | ||
| string signingInput = $"{Base64UrlEncode(header)}.{Base64UrlEncode(payload)}"; | ||
| using HMACSHA256 hmac = new(sharedSecret); | ||
| byte[] signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(signingInput)); | ||
|
|
||
| return $"{signingInput}.{Base64UrlEncode(signature)}"; | ||
| } | ||
|
|
||
| private static string Base64UrlEncode(string value) => Base64UrlEncode(Encoding.UTF8.GetBytes(value)); | ||
|
|
||
| private static string Base64UrlEncode(byte[] bytes) => | ||
| Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); | ||
|
|
||
| private static string GenerateDigest(string data) | ||
| { | ||
| using SHA256 sha256 = SHA256.Create(); | ||
|
|
||
| return Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(data))); | ||
| } | ||
|
|
||
| private static string GetCertificateKeyId(X509Certificate2 certificate) | ||
| { | ||
| Match subjectSerialNumber = Regex.Match(certificate.Subject, @"(?:^|,\s*)SERIALNUMBER\s*=\s*([^,]+)", RegexOptions.IgnoreCase); | ||
| if (subjectSerialNumber.Success) | ||
| return subjectSerialNumber.Groups[1].Value.Trim(); | ||
|
|
||
| string decodedSerialNumber = DecodeHexSerialNumber(certificate.SerialNumber); | ||
|
|
||
| return string.IsNullOrWhiteSpace(decodedSerialNumber) ? certificate.SerialNumber : decodedSerialNumber; | ||
| } | ||
|
|
||
| private static string DecodeHexSerialNumber(string serialNumber) | ||
| { | ||
| if (string.IsNullOrEmpty(serialNumber) || serialNumber.Length % 2 is not 0 || serialNumber.Any(character => !Uri.IsHexDigit(character))) | ||
| return string.Empty; | ||
|
|
||
| byte[] bytes = Enumerable.Range(0, serialNumber.Length / 2) | ||
| .Select(index => Convert.ToByte(serialNumber.Substring(index * 2, 2), 16)) | ||
| .ToArray(); | ||
|
|
||
| string decoded = Encoding.ASCII.GetString(bytes); | ||
| return decoded.All(character => char.IsLetterOrDigit(character)) ? decoded : string.Empty; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| namespace Dynamicweb.Ecommerce.CheckoutHandlers.CyberSource; | ||
|
|
||
| internal enum RestAuthenticationMethod | ||
| { | ||
| Certificate, | ||
| SharedSecret | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.