How do I use C# to get a signed URL from CloudFront? - c#

There are several similar questions but not one quite the same:
We have an S3 bucket with CloudFront on it configured to use signedURLs. I can use the command line to generate a signed URL and access it. When I try to do this via C# the signed URL generated is not valid.
This is the command line which returns a valid url:
aws cloudfront sign --url https://MyPath.com/testfile.txt
--key-pair-id "keypairIDvalue" --private-key file://bas_key.pem --date-less-than 2022-01-01
The code is this:
static void Main(string[] args)
{
// technique 1
string policyDoc = Amazon.CloudFront.AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
#"https://MyPath/testfile.txt",
DateTime.Today.AddDays(+4),
"myIPAddress");
string signurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.SignUrl(
#"https://MyPath/testfile.txt",
"KeypairID",
new StreamReader(#"c:\keys\Bas_key.pem"),
policyDoc);
// the signurl does not work
// technique 2
string newurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.GetCustomSignedURL(
#"https://MyPath/testfile.txt",
new StreamReader(#"c:\keys\Bas_key.pem"),
"KeypairID",
DateTime.Today.AddDays(4),
DateTime.Today.AddDays(-1),
"MyIPAddress");
// newurl is different to signurl but also does not work
Console.WriteLine(newurl);
}
Most examples I have seem to have a lot of extra code to do various bits and bobs but here everything is setup and configured. I just need the API command to get the URL, the documentation seems to imply this is an expected way of doing this but I cannot get it to work. Neither of the above techniques work.
Can anyone see what I have done wrong?

Fixed it!
The working code is this!
static void Main(string[] args)
{
// technique 1
string policyDoc = Amazon.CloudFront.AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
null,
DateTime.Today.AddDays(+1),
null);
string signurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.SignUrl(
#"https://MyPath/testfile.txt",
"KeypairID",
new StreamReader(#"c:\keys\Bas_key.pem"),
policyDoc);
Console.WriteLine(signurl);
}

Related

Trying to find how a specific 32 hex character webform is generated from Netgear Managed Switch local UI webpage

I am trying to simulate navigating Netgear Managed Switch (GC108PP) local UI webpage in C#. When sending HttpWebRequest using a Chrome browser, I've learned using Fiddler - there are 3 WebForms that are generated when hitting this URL:
http://192.168.50.101
ends up being:
http://192.168.50.101/cgi/get.cgi?cmd=home_login&dummy=1582137153063&bj4=3f104a21e12a9584d36372142f16e35b
WebForms:
cmd=home_login
dummy=1582137153063 (time since epoch, this one was easy to figure out)
bj4=3f104a21e12a9584d36372142f16e35b (trying to figure out how to generate this one)
There is no HTTP API to reference from Netgear. I have tried just generating a 32 char string with:
private static Random random = new Random();
public static string randomString(int length)
{
const string chars = "abcdef0123456789";
return new string(Enumerable.Repeat(chars, length).Select(s =>s[random.Next(s.Length)]).ToArray());
}
However, I get ERROR 400 Bad Request.If I use a bj4 key/ID that gets generated by my browser statically in my code it works, but I want to be generating this webform properly.
Any ideas on how this WebForm might be be generated?
Found it in the JS...
function gotoLogin()
{
document.cookie = \"testcookie\";
cookieEnabled = (document.cookie.indexOf(\"testcookie\") != -1) ? true : false;
if (cookieEnabled == false)
{
alert(\"Browser does not accept cookies. Please configure your browser to accept cookies in order to access the Web Interface.\");
}
var fileVer = (new Date().getTime());
var url = \"login.html?aj4=\"+fileVer;
url = url + '&bj4=' + md5(url.split('?')[1]); //here!!!
window.location.href=url;
}

AWS Machine Learning RealTimePredictor returns UnknownoperationException in C#

Using Visual Studio, and AWS .NET V 3.0.
I'm trying to perform a real-time Predict operation, and to verify the basic setup works, I first perform a GetMLModel() which works and returns the endpoint (Somewhere in the documentation is was mentioned to use that result as the service endpoint, but it's the same that is listed in the console). Is has status "READY", so far so good.
The exception occurs below on the line below "Prediction P = RTP.Predict(Data)". Data contains a Dictionary with all the prediction values.
Error: Error making request with Error Code UnknownOperationException and Http Status Code BadRequest. No further error information was returned by the service.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate();
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
GetMLModelResponse MLMOdelResp = MLClient.GetMLModel("xxx"); // <-- WORKS
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
Console.WriteLine(MLConfig.ServiceURL);
MLConfig.Validate();
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data); // <----------------EXCEPTION HERE
}
(Obviously replace xxx with relevant values) :)
It turns out that this line:
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
cases the MLConfig.RegionEndpoint to be reset. Even though the documentation indicates the RegionEndpoint can be determined from the ServiceURL (I'm pretty sure I read that), the RegionEndpoint needs to be set again before the RTP.Predict(Data) call.
Once I figured that out, I was able to reduce the code to just this, in case anyone else needs help. I guess adding too much information to the Configuration is NOT a good thing, as the AWS. NET library seems to figure all this out on its own.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate(); // Just in case, not really needed
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data);
}

Cache player with GameSparks and Unity

I am new to gamesparks, but so far I have set up a login/register function, which works like it should, but... How do I ensure that the user don't have to login next time he or she opens the app?
I found this in which I read that I can just run this:
GameSparkssApi.isAuthenticated().
First off all, in all other tutorials it states that it should be: GameSparks.Api.xxxx. Even when trying this I do not find isAuthenticated() anywhere.
GameSparks.Api.isAuthenticated();
I am hoping that someone can cast some light on this.
You can use Device Authentication for this purpose. This method of auth sets an access token for the device you are on. This token is stored and the client and gotten in the request. these requests are structured like so:
new GameSparks.Api.Requests.DeviceAuthenticationRequest()
.SetDeviceId(deviceId)
.SetDeviceModel(deviceModel)
.SetDeviceName(deviceName)
.SetDeviceOS(deviceOS)
.SetDeviceType(deviceType)
.SetDisplayName(displayName)
.SetOperatingSystem(operatingSystem)
.SetSegments(segments)
.Send((response) => {
string authToken = response.AuthToken;
string displayName = response.DisplayName;
bool? newPlayer = response.NewPlayer;
GSData scriptData = response.ScriptData;
var switchSummary = response.SwitchSummary;
string userId = response.UserId;
});
You can find more on this method in our documentation: https://api.gamesparks.net/#deviceauthenticationrequest
Regards Patrick, GameSparks.

IP data lookup - C#

Okay, so I've googled on several occasions regarding this, but each one suggests respectfully decent choices like : "Selenium" which works fine, but isn't use-able without firefox (or even within an API to my knowledge?).
I have this code :
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadData(url);
}
}
Then I also have this code :
byte[] result = GetFileViaHttp(#"http://ip-lookup.net/");
string str = Encoding.UTF8.GetString(result);
richTextBox1.Text = str;
Works fine, returns my IP's information, but I want to automate this with other IP addresses, rather than return my own.
How would this be done ?
By this I mean, I want the API to take txtBox1.Text (IP) & print the details into richTextBox1.Text (Host/Country) ..
How could this be done ?
I looked around the site and found a help document that details exactly what you want.
Simply pass the IP value as an unnamed query string parameter:
http://ip-lookup.net/?127.0.0.1
In your code:
byte[] result = GetFileViaHttp(string.Format("http://ip-lookup.net?{0}", ipAddress));
where you are injecting a string ip address as ipAddress.
You can find their help page here. I looked for a legal agreement but I wasn't able to find one, so please use at your own risk and discretion.
UPDATE:
If you are getting 403s, you need to pass along a user agent header. Your WebClient instance can be modified to include a header in the request.
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
client.Headers.Add("User-Agent: Other");
return client.DownloadData(url);
}
}

How to work with the BING REST Api

How exactly do you use the BING REST api (specifically the ROUTES part) to get a driving distance in ASP.NET.
I have searched high and low on Google for this answer and none is forthcoming.
I have found url strings such as:
http://dev.virtualearth.net/REST/v1/Routes/Driving?waypoint.0=redmond&heading=90&waypoint.1=seattle&du=mi&key=BingMapsKey
That's great! But how to call it from ASP?
I have also found this code:
private void GetResponse(Uri uri, Action<HttpResponse> callback)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(HttpResponse));
callback(ser.ReadObject(a.Result) as HttpResponse);
}
};
wc.OpenReadAsync(uri);
}
Which is a "generic method to make web requests". But, again, how do you call it? I find it confusing that it doesn't require a return type.
In order to call it, I have found code like this:
string key = "YOUR_BING_MAPS_KEY or SESSION_KEY";
string query = "1 Microsoft Way, Redmond, WA";
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key));
GetResponse(geocodeRequest, (x) =>
{
Console.WriteLine(x.ResourceSets[0].Resources.Length + " result(s) found.");
Console.ReadLine();
});
But when I add this to the project, I get every error under the sun coming up. So, I am stuck.
I am a total ASP beginner and haven't found any online documentation any help at all.
p.s. I do have a BING api key and do use it in the code above.
I am not an expert in this, but the below compiles for me. Also make sure to add the data constructs as mentioned in the BING documentation:
protected void Page_Load(object sender, EventArgs e)
{
string key = "YOUR KEY";
string query = "ADDRESS";
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key));
GetResponse(geocodeRequest, (x) =>
{
Console.WriteLine(x.ResourceSets[0].Resources.Length + " result(s) found.");
Console.ReadLine();
});
}
Quoting from another stackoverflow question:
The bottom of the documentation you are using points to the Data contracts you need for the REST services which are available here: http://msdn.microsoft.com/en-us/library/jj870778.aspx
Simply create a empty C# file and copy in paste in the C# Data Contracts. Then add the namespace to this class:
using BingMapsRESTService.Common.JSON;

Categories