Amazon CloudFront invalidation in ASP.Net - asp.net

I am not sure how to send a request using ASP.Net to Amazon CloudFront to invalidate an object.
The details are here http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html
but I am not sure how to implement this in ASP.Net.

The accepted answer no longer works as of the latest version of the AWS SDK for .NET (1.5.8.0). This should do the trick:
using Amazon;
using Amazon.CloudFront.Model;
...
var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
DistributionId = distributionID,
InvalidationBatch = new InvalidationBatch {
Paths = new Paths {
Quantity = arrayofpaths.Length,
Items = arrayofpaths.ToList()
},
CallerReference = DateTime.Now.Ticks.ToString()
}
});

Got it working, here it is if anyone else finds it useful.
public static void InvalidateContent(string distributionId, string fileName)
{
string httpDate = Helpers.GetHttpDate();
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = #"<InvalidationBatch>" +
" <Path>/" + fileName + "</Path>" +
" <CallerReference>" + httpDate + "</CallerReference>" +
"</InvalidationBatch>";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers.Add("x-amz-date", httpDate);
Encoding ae = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);
webRequest.ContentLength = data.Length;
Stream newStream = webRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate()
{
// Setting the Culture will ensure we get a proper HTTP Date.
string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
return date;
}

Here's a python version of the above, if anyone finds it useful
from datetime import datetime
import urllib2, base64, hmac, hashlib
def getHTTPDate():
return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")
def submitInvalidationRequest(fileName,distributionId):
url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
httpDate = getHTTPDate();
postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)
headers = {"ContentType": "text/xml",
"x-amz-date": httpDate,
"Authorization":"AWS " + AWSAccessKeyId + ":" + base64.b64encode( sig.digest() )}
req = urllib2.Request(url,postData,headers)
return urllib2.urlopen(req).read()

using the AWSSDK .net api wrapper from amazon makes this task even easier.
using Amazon.CloudFront.Model;
...
var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);

Here's perl:
use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);
#ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";
my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];
my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;
my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
<Path>$invalid_url</Path>
<CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE
my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));
my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
"Content" => $post_data,
"ContentType" => "text/xml",
"x-amz-date" => $date,
"Authorization" => "AWS $accesskey:$sig");
print $res->status_line, "\n", $res->content;

Related

Oauth 401 Error invalid signature when requesting to woocommerce rest api with httpclient .net core

First of all I know I can use trusted libraries to generate oAuth header signature but I spent a lot of time to generate this signature and I want to know why it's not working.
I have ConsumerKey and ConsumerSecret to access woocommerce rest api.
I write a method to generate BaseSignatureString and another method to get HMAC-SHA1 :
public static string GetoAuthToken(string conKey, string conSecret)
{
string timestamp = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
string nonce = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(timestamp
+ timestamp + timestamp));
var signatureBaseString = "GET&" + Uri.EscapeDataString("https://loomina.ir/wp-json/wc/v3/products") + "&";
signatureBaseString += Uri.EscapeDataString($"oauth_consumer_key={conKey}&");
signatureBaseString += Uri.EscapeDataString($"oauth_nonce={nonce}&");
signatureBaseString += Uri.EscapeDataString($"oauth_signature_method=HMAC-SHA1&");
signatureBaseString += Uri.EscapeDataString($"oauth_timestamp={timestamp}&");
signatureBaseString += Uri.EscapeDataString($"oauth_version=1.0");
string SHA1HASH = GetSha1Hash(conSecret + "&" , signatureBaseString);
string Header = $"oauth_consumer_key=\"{conKey}\",oauth_timestamp=\"{timestamp}\",oauth_signature_method=\"HMAC-SHA1',oauth_nonce=\"{nonce}\",oauth_version=\"1.0\",oauth_signature=\"{SHA1HASH}\"";
return Header;
}
Get SHA1 Hash :
public static string GetSha1Hash(string key, string baseSignatureString)
{
var encoding = new ASCIIEncoding();
byte[] keyBytes = encoding.GetBytes(key);
byte[] messageBytes = encoding.GetBytes(baseSignatureString);
string Sha1Result = string.Empty;
using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes))
{
var Hashed = SHA1.ComputeHash(messageBytes);
Sha1Result = Convert.ToBase64String(Hashed);
}
return Sha1Result;
}
Request part :
var oAuthSignature = Utility.GetoAuthToken(websites.CustomerKey, websites.CustomerSecret);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", oAuthSignature);
var response = await _client.GetAsync($"{websites.Url}/wp-json/wc/v3/products/");
var result = await response.Content.ReadAsStringAsync();
The status of request is 401 Not Authorized (Invalid signature)

Follow Company issue (LinkedIn API)

I am trying to follow a company without success.
I have generated an access token for all scopes which also works for other functions with the API:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
The below code reaches the end and shows the MessageBox with message:
"BadRequest,Can not parse JSON company document.\nRequest body:\n\nError:\nnull"
I will be happy for help. I have follwed the below documentation but it doesn't exactly show how to follow the company, so it leaves me with this question and example below:
https://developer.linkedin.com/documents/company-follow-and-suggestions
String companyID = "9288340";
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies/id=" + companyID + "?oauth2_access_token=MYTOKENGOESHERE";
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());
After a lot of testing, I just managed to be able to follow a company.
So the below code is working:
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token=MYTOKENGOESHERE";
var BODY = new
{
id = "9288340" //companyID
};
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(BODY);
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());

401 System.UnauthorizedAccessException when access Dropbox With SharpBox API

The code
config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
as DropBoxConfiguration;
//config.AuthorizationCallBack = new Uri("http://localhost:61926/DBoxDemo.aspx");
requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, "KEY", "SECRET");
//Session["requestToken"] = requestToken;
string AuthoriationUrl = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(
config, requestToken);
Process.Start(AuthoriationUrl);
accessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(
config, "xxxxxxxxxxxxx", "xxxxxxxxxxxxx", requestToken);
CloudStorage dropBoxStorage = new CloudStorage();
var storageToken = dropBoxStorage.Open(config, accessToken);
var publicFolder = dropBoxStorage.GetFolder("/");
// upload a testfile from temp directory into public folder of DropBox
String srcFile = Environment.ExpandEnvironmentVariables(#"C:\Test\MyTestFile.txt");
var rep = dropBoxStorage.UploadFile(srcFile, publicFolder);
MessageBox.Show("Uploaded Successfully..");
**dropBoxStorage.DownloadFile("/MyTestFile.txt",
Environment.ExpandEnvironmentVariables("D:\\test"));**
MessageBox.Show("Downloaded Successfully..");
dropBoxStorage.Close();
This is the Error shown in Visual Studio.
SharpBox has a bug that only occurs in .NET 4.5, because the behavior of the class System.Uri has changed from 4.0 to 4.5.
The method GetDownloadFileUrlInternal() in DropBoxStorageProviderService.cs generates an incorrect URL, because it changes a slash in %2f. In .NET 4.0, this URL will be converted correctly back through the System.Uri object in the method GenerateSignedUrl() in OAuthUrlGenerator.cs.
I have changed the method GetDownloadFileUrlInternal() from this...
public static String GetDownloadFileUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
// cast varibales
DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession;
// gather information
String rootToken = GetRootToken(dropBoxSession);
String dropboxPath = GenericHelper.GetResourcePath(entry);
// add all information to url;
String url = GetUrlString(DropBoxUploadDownloadFile, session.ServiceConfiguration) + "/" + rootToken;
if (dropboxPath.Length > 0 && dropboxPath[0] != '/')
url += "/";
url += HttpUtilityEx.UrlEncodeUTF8(dropboxPath);
return url;
}
...to this...
public static String GetDownloadFileUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
// cast varibales
DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession;
// gather information
String rootToken = GetRootToken(dropBoxSession);
// add all information to url;
String url = GetUrlString(DropBoxUploadDownloadFile, session.ServiceConfiguration) + "/" + rootToken;
ICloudFileSystemEntry parent = entry.Parent;
String dropboxPath = HttpUtilityEx.UrlEncodeUTF8(entry.Name);
while(parent != null)
{
dropboxPath = HttpUtilityEx.UrlEncodeUTF8(parent.Name) + "/" + dropboxPath;
parent = parent.Parent;
}
if (dropboxPath.Length > 0 && dropboxPath[0] != '/')
url += "/";
url += dropboxPath;
return url;
}
and currently it works with .NET 4.5. It may exist a better way to fix the problem, but currently no misconduct noticed.

asp.net amazon itemsearch

I'm using visual studio 2008 and trying to do API itemsearch like books or something.
I am using just accessKeyId, but when I click my "search" button to search books, then comes signature error.
Do I need to use secretKeyID also?
I just created new ASP.Net web site in visual studio Or I have to use AWS SDK for.Net package?
Can somebody please give a good advice.
Thanks!
Signature error means you did not create a request signature properly. You should use the SprightlySoft AWS Component for .NET. It's free and it supports the Product Advertising API. Get it at http://sprightlysoft.com/. The AWS SDK for.NET does not work with the Product Advertising API.
Here is an example of calling ItemSearch with the SprightlySoft component.
//Product Advertising API, ItemSearch: http://docs.amazonwebservices.com/AWSECommerceService/2010-10-01/DG/ItemSearch.html
SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();
String RequestURL;
RequestURL = "https://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&Version=2010-10-01";
RequestURL += "&AWSAccessKeyId=" + System.Uri.EscapeDataString(TextBoxAWSAccessKeyId.Text) + "&SignatureVersion=2&SignatureMethod=HmacSHA256&Timestamp=" + Uri.EscapeDataString(DateTime.UtcNow.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z"));
RequestURL += "&Actor=" + System.Uri.EscapeDataString("Tom Cruise");
RequestURL += "&SearchIndex=DVD";
RequestURL += "&ResponseGroup=" + System.Uri.EscapeDataString("ItemAttributes,Reviews");
RequestURL += "&Sort=salesrank";
RequestURL += "&ItemPage=1";
String RequestMethod;
RequestMethod = "GET";
String SignatureValue;
SignatureValue = MyREST.GetSignatureVersion2Value(RequestURL, RequestMethod, "", TextBoxAWSSecretAccessKey.Text);
RequestURL += "&Signature=" + System.Uri.EscapeDataString(SignatureValue);
Boolean RetBool;
RetBool = MyREST.MakeRequest(RequestURL, RequestMethod, null);
System.Diagnostics.Debug.Print(MyREST.LogData);
String ResponseMessage = "";
if (RetBool == true)
{
System.Xml.XmlDocument MyXmlDocument;
System.Xml.XmlNamespaceManager MyXmlNamespaceManager;
System.Xml.XmlNode MyXmlNode;
System.Xml.XmlNodeList MyXmlNodeList;
MyXmlDocument = new System.Xml.XmlDocument();
MyXmlDocument.LoadXml(MyREST.ResponseString);
MyXmlNamespaceManager = new System.Xml.XmlNamespaceManager(MyXmlDocument.NameTable);
MyXmlNamespaceManager.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2010-10-01");
MyXmlNodeList = MyXmlDocument.SelectNodes("amz:ItemSearchResponse/amz:Items/amz:Item", MyXmlNamespaceManager);
if (MyXmlNodeList.Count == 0)
{
ResponseMessage = "No items exist.";
}
else
{
foreach (System.Xml.XmlNode ItemXmlNode in MyXmlNodeList)
{
MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:Title", MyXmlNamespaceManager);
ResponseMessage += "Title = " + MyXmlNode.InnerText;
MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:ListPrice/amz:FormattedPrice", MyXmlNamespaceManager);
ResponseMessage += " ListPrice = " + MyXmlNode.InnerText;
ResponseMessage += Environment.NewLine;
}
}
MessageBox.Show(ResponseMessage);
}
else
{
MessageBox.Show(MyREST.ResponseStringFormatted);
}

WebDAV with J2ME

Is there a way to use WebDAV with J2ME (some libraries or manual coding)?
I've tried:
- javax.microedition.io.HttpConnection, but "SEARCH" method not supported there
- javax.microedition.io.SocketConnection with Http request - nothing returns in response
Maybe something wrong with my code or HTTP header:
String response = "";
String query = "<?xml version='1.0'?> "
+ "<g:searchrequest xmlns:g='DAV:'> "
+ "<g:sql> "
+ "SELECT 'DAV:displayname' "
+ "FROM 'http://exchangeserver.com/Public/' "
+ "</g:sql> "
+ "</g:searchrequest> ";
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://exchangeserver.com:8080");
DataOutputStream dout =
new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = "username" + ":" + "password";
byte[] encoded =
Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "SEARCH /Public/ HTTP/1.1\r\n"
+"Content-Type:text/xml\r\nContent-Length:"
+ len
+ "\r\nAuthorization:Basic "
+ new String(encoded)
+ "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();
What do you mean by "nothing returns"? No response body? No status code?
I recommend to trace what's going on on the "wire"...
UPDATE: have you tried adding a host header?
Julian +1 you was right for Host property, QRSO +1, thanks to all!
So,
- I have found free WebDAV service MyDisk.se (SEARCH not allowed, so I used PROPFIND)
- used WFetch to play around with WebDAV request
- used Network Monitor to compare requests from WFetch and my app.
:) Finally it's working!
Result code:
String response = "";
String query = "<?xml version='1.0' encoding='UTF-8'?>\r\n"
+ "<d:propfind xmlns:d='DAV:'>\r\n"
+ "<d:prop><d:getcontenttype/></d:prop>\r\n"
+ "<d:prop><d:getcontentlength/></d:prop>\r\n"
+ "</d:propfind>\r\n";
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://79.99.7.153:80");
DataOutputStream dout = new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = "login" + ":" + "password";
byte[] encoded = Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "PROPFIND /mgontar/ HTTP/1.1\r\n"
+ "Depth: 1\r\n"
+ "Host: mydisk.se:80\r\n"
+ "Accept: */*\r\n"
+ "Content-Type: text/xml\r\n"
+ "Content-Length: " + len
+ "\r\nAuthorization: Basic " + new String(encoded)
+ "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();
FYI If you are testing on an actual mobile phone, then there is a fair chance your mobile network operator could be blocking non-HTTP traffic.
You might want to first check that you can make GET and POST requests to the server first.

Resources