How to verify a shopify webhook request in asp.net - asp.net

Can someone explain how do I compute a HMAC
===============
To verify that the request came from Shopify, compute the HMAC digest according to the following algorithm and compare it to the value in the X-Shopify-Hmac-SHA256 header. If they match, you can be sure that the Webhook was sent from Shopify and the data has not been compromised.
Each Webhook request includes a X-Shopify-Hmac-SHA256 header which is generated using the app's shared secret, along with the data sent in the request.
I have the secret key... how can I combine the secret key + the data in the request to generate a HMAC

The easiest way is to use the ShopifySharp Library. You can use the Nuget package and install it in your project.
This is an example taken from the ShopifySharp website for validating webhooks:
NameValueCollection requestHeaders = Request.Headers;
Stream inputStream = Request.InputStream;
if(AuthorizationService.IsAuthenticWebhook(requestHeaders, inputStream, shopifySecretKey))
{
//Webhook is authentic.
}
else
{
//Webhook is not authentic and should not be acted on.
}
If you don't want to use ShopifySharp, you can see how they implemented it in the source code.

Related

Encryption key retrieve on http call to the API?

Can you tell me if the following flow is good practice for retrieving encryption key?
So I have an Angular app which has custom encryption service created by me and a npm library, which now uses simple string value for key.
I also store access token inside a cookie and the value is encrypted.
Is it good practice, while executing a standard CRUD operation method against my API, first in this method to execute a separate http get request to get the encryption key from the API (from a separate endpoint), then de-crypt the cookie and THEN send it in the http request?
For example, look at this pseudo-code:
getAllProductsAsAdmin(): Observable<any>{
let encryptionKey = callApiAndGetKeyMethod(this.encryptionKeyApiUrl);
let decryptedCookie = decryptCookie(this.existingCookie, encryptionKey);
this.headers = this.headers.set('Authorization', decryptedCookie);
return this.httpClient.get<IGetProductAdminModel[]>(this.getAllProductsAsAdminUrl, {headers: this.headers})
.pipe(
tap(data => console.log('All:',JSON.stringify(data))),
catchError(this.handleError)
);

Can I use my test environment merchant ID and keys to test a flex microform post?

I'm getting started understanding what's required for Cybersource's Flex Microform integration. But to start with, I'm hoping to be able to see a valid response using my merchant ID, shared secret key and the general key that comes with generating the secret on the cybersource api reference page: https://developer.cybersource.com/api-reference-assets/index.html#flex-microform_key-generation_generate-key
This is using the HTTP Signature method and ChasePaymentech (default) processor.
If I use the default settings they supply and choose to do a test POST to here https://apitest.cybersource.com/flex/v1/keys?format=JWT&
The JSON response is good with no complaints of authentication.
If I try to do the same POST with my test environment merchant ID and keys I generated in my merchant environment here: https://ubctest.cybersource.com/ebc2/app/PaymentConfiguration/KeyManagement the POST response will return a 401 with this JSON:
{
"response": {
"rmsg": "Authentication Failed"
}}
Is this developer.cybersource.com site a valid place to perform this kind of test? Are there any other steps I need to do in the merchant account to have this Authenticate?
I'm just getting started on figuring out the CyberSource Flex Micro Form code out myself and it's pretty straight forward from what I can see. If you don't have the proper SDK already pulled in, you can fetch it from https://github.com/CyberSource
I had to use Composer to fetch all the dependencies but once I did, I was able to load up the microform checkout page in my browser window successfully. Make sure you edit the ExternalConfiguration file with your credentials that you setup in CyberSource.
The apiKeyId value is the value you can find in your CyberSource account under Key Management. This is the value with the dashes in it.
The secretKey value is the value you should have downloaded from CyberSource that is your public key. This is the value without the dashes and probably has a few slashes / in it.
That's all I had to do in my setup to get the first successful authentication / token on my end.

Shopee Open Platform API always response "Invalid token"

I'm sorry in advance if something bring you here and I talk about a platform that's not really well-known over the world despite featuring a well-known person dancing in their commercial.
It's Shopee Open Platform API I talk about. I was trying to follow very properly their instruction here.
https://open.shopee.com/documents?module=63&type=2&id=51
But stuck instantly at step 5 : Shop Authorization. First, I've been given a test partner id, a test key, and I need to set manually the test redirect URL. I have to generate authorization token from all given information. Firstly I need to create a token base string by concatenating the test key with URI component encoded string of the URL. It turns into something like this.
9b754aca01a5d719cb70c5778294dae6ff90fcc68c82908ee480a36ff901d181https%3A%2F%2Fwww.unwelldocumented.com
To generate the authorization token, it says I need to do hexencode(sha256(token_base_string)). It returned a very long integer.
32373935663639356636346266303137613465396239383361373334646133656530313333393762636138396364663037366566313366313436316534303761
So I just assumed everything is fine and that is the authorization token. But when I send this...
https://partner.uat.shopeemobile.com/api/v1/shop/auth_partner?id=(test_partner_id)&token=(authorization_token)&redirect=(test_redirect_URL)
... suddenly I get this
{
"error": "error_auth",
"msg": "Invalid token",
"request_id": "30a4b6b0074541bdd88260a33f155ca6"
}
In order to solve this, you have to understand that SHA256 is an Encryption hash function. Please research more on SHA256 on your specific language.
For this very specific case, your SHA256 token should be as below.
Before SHA256:
9b754aca01a5d719cb70c5778294dae6ff90fcc68c82908ee480a36ff901d181https%3A%2F%2Fwww.unwelldocumented.com
After SHA256:
2795f695f64bf017a4e9b983a734da3ee013397bca89cdf076ef13f1461e407a
The rest of your steps seems correct.

Encoded / Encrypted body before verifying a Pact

A server I need to integrate with returns its answers encoded as a JWT. Worse, the response body actually is a json, of the form:
{d: token} with token = JWT.encode({id: 123, field: "John", etc.})
I'd like to use a pact verification on the content of the decoded token. I know I can easily have a pact verifying that I get back a {d: string}, I can't do an exact match on the string (as the JWT contains some varying IDs). What I want is the following, which presumes the addition of a new Pact.JWT functionality.
my_provider.
upon_receiving('my request')
.with(method: :post,
path: '/order',
headers: {'Content-Type' => 'application/json'}
).will_respond_with(
status: 200,
headers: {'Content-Type' => 'application/json; charset=utf-8'},
body: {
d: Pact::JWT( {
id: Pact.like(123),
field: Pact.term(generate: "John", matcher: /J.*/
},signing_key,algo
)
})
Short of adding this Pact::JWT, is there a way to achive this kind of result?
I am already using the pact proxy to run my verification. I know you can modify the request before sending it for verification (How do I verify pacts against an API that requires an auth token?). Can you modify the request once you receive it from the proxy server?
If that's the case, I can plan for the following work around:
a switch in my actual code to sometimes expect the answers decoded instead of in the JWT
run my tests once with the swich off (normal code behaviour, mocks returns JWT data encoded.
run my tests a second time with the swich off (code expect data already decoded, mocks return decoded data.)
use the contract json from this second run
hook into the proxy:verify task to decode the JWT on the fly, and use the existing pact mechanisms for verification. (Step that I do not know how to do).
My code is in ruby. I do not have access to the provider.
Any suggestions appreciated! Thanks
You can modify the request or response by using (another) proxy app.
class ProxyApp
def initialize real_provider_app
#real_provider_app = real_provider_app
end
def call env
response = #real_provider_app.call(env)
# modify response here
response
end
end
Pact.service_provider "My Service Provider" do
app { ProxyApp.new(RealApp) }
end
Pact as a tool, I don't expect it to give this behavior out of the box.
In my opinion, the best is,
Do not change source code only for tests
Make sure your tests verifies encoded json only (generate encoded expected json in test & verify that with actual)

Asp.net and OAuth simple example without existing Library

I try to get a request token from Twitter OAuth and I always received a server error 401 when I try to get the response. I don't want to used an existing library because I try to learn Oauth and maybe build my own library. This is my simple code :
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth/request_token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder sbParams = new StringBuilder();
sbParams.Append("OAuth ");
sbParams.AppendFormat("oauth_consumer_key={0},", "[COMSUMERKEY]");
sbParams.AppendFormat("oauth_signature_method={0},", "PLAINTEXT");
sbParams.AppendFormat("oauth_signature={0},", HttpUtility.UrlEncode("[COMSUMER_SECRET]&"));
sbParams.AppendFormat("oauth_timestamp={0},", ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString());
sbParams.AppendFormat("oauth_nonce={0},", "asdfalkjpoijwpeonpoaisudfnpowieuyfpasosdfdn");
sbParams.AppendFormat("oauth_version={0},", "1.0");
sbParams.AppendFormat("oauth_callback={0}", HttpUtility.UrlEncode(Request.Url.ToString()));
request.Headers.Add("Authorization", sbParams.ToString());
// Get the response.
WebResponse response = request.GetResponse();
From http://oauth.net/core/1.0a/#http_codes You know these
HTTP 401 Unauthorized
Invalid Consumer Key
Invalid / expired Token
Invalid signature
Invalid / **used nonce
The "used nonce" thing may be a problem. You need to generate a random string. From http://oauth.net/core/1.0a/#nonce
A nonce is a random string, uniquely generated for each request
Onto the serious business. You are not supposed to transmit your consumer secret, once you ever received it! Many OAuth libraries have a
request_request_token(consumer_key,consumer_secret)
Despite appearances, the consumer_secret is never transmitted. It is used at client-side, for verification of server's response. (A similar verification occurs at server-side too)
And you dont put in any static values for signing requests. From http://oauth.net/core/1.0a/#signing_process
All Token requests and Protected Resources requests MUST be signed by the Consumer and verified by the Service Provider.
Bottomline: do read the http://oauth.net/core/1.0a/ article to see how the protocol works. And choose a hands-on OAuth library that doesnt abstract too much details (The oauth-php library I used came with SQL tables and managed data stores and session memory by itself).

Resources