How to pass in api key? - c#

I have searched everywhere and I cannot find out how to pass my API key in with my request. I am setup to run from a specific IP address. I keep hitting my limit though. I think I am also hitting my time limits. I will introduce a sleep in my code. Otherwise, is there anything else I can check?? I am using the distance matrix with json output. I have turned on Google Maps API V3. I have a key and have a project. It seems like the service is still treating me like a free customer.
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&mode=driving&language=en-EN&sensor=false&units=imperial";
I have also tried two more approaches with my key and I get a denied request from both of them.
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&key=mykey&mode=driving&language=en-EN&sensor=false&units=imperial";
and
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&key={mykey}&mode=driving&language=en-EN&sensor=false&units=imperial";
I was not sure if the curly braces were required or not. Both of the later lines of code result in request denials.

Looks to me like you just pass the key right in the URL, at least for the regular maps API. Take a look at the "Hello World" example in the documentation. It might work the same for the distance matrix. Have you tried it that way?

Related

How to get current domain name in ASP.NET

I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;
My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com
I want to get somedomainname.com
Please give me an idea how to get the current domain name.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.
Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.
You can try the following code :
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Getting the port is just like other people have said.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for
You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Here is a quick easy way to just get the name of the url.
var urlHost = HttpContext.Current.Request.Url.Host;
var xUrlHost = urlHost.Split('.');
foreach(var thing in xUrlHost)
{
if(thing != "www" && thing != "com")
{
urlHost = thing;
}
}
To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
string domainName = HttpContext.Request.Host.Value;
this line should solve it
Try this:
#Request.Url.GetLeftPart(UriPartial.Authority)

Origin Search Phrase

Does anyone know if there is a way to capture the search phrase used to get to your site? Do the search engines forward that information in any header values?
I have looked through all of the Request.ServerVariables and have not been able to find anything to do with the origin of the user (other than HTTP_REFERER).
I can see some anonymous information in Google Analytics but I am wanting to bind this information to user records upon account creation.
Any help is appreciated.
Yes - UrlReferrer is where you would have to look. But as google search (by default) runs via https it will not send any Url Referrer. So you are out of luck here - sorry (or maybe good for the users ;-) ).
If you get visited by http you could try some fancy approach like:
http://www.codeproject.com/Tips/127681/Get-search-key-word-from-the-referrer-url
If the page before loading your page was the search engine, you can use UrlReferrer to get it and then maybe parse it to get the values
Uri MyUrl = Request.UrlReferrer;
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>");
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>");
Hope it helps

How to generate pre-signed Amazon S3 url for a vanity domain, using amazon sdk?

I have an s3 bucket called foo.example.com, which is all CNAMEd correctly.
I'm switching to the latest AWS .net SDK.
I wish to generate pre signed url like:
http://foo.example.com/myfile.txt?s3_params_here
Note the vanity cname there.
I have:
string bucketName = "foo.example.com";
AmazonS3Client s3Client = new AmazonS3Client("bar", "xxx",
new AmazonS3Config
{
ServiceURL = bucketName,
CommunicationProtocol = Protocol.HTTP
});
string key = "myfile.txt";
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
string url = s3Client.GetPreSignedURL(request);
the url I get is something like:
http://foo.example.com.foo.example.com/myfile.txt?AWSAccessKeyId=bar&Expires=1331069777&Signature=234KoUUvfE1nCcs2vLj9RQUhqF8%3D
Which is clearly wrong.
I've tried a buch of different variations with ServiceURL, bucketname, etc, but nothing seems to work.
I can't find any good documentation - what is the correct way to do this?
Thanks.
Update [workaround]
I've meanwhile resolved the contradicting test results of mine, which stem from respectively unsystematic testing and URL manipulations. The following workaround does the trick for me (i.e. tested and reproducible), simply starting from your solution:
string bucketName = "foo.example.com";
// [...]
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(32))
.WithProtocol(Protocol.HTTP);
Now this yields the erroneous URL with a duplicate domain name, i.e. http://foo.example.com.foo.example.com/myfile.txt?[...]
The duplicate can simply be removed though, e.g.:
string url = s3Client.GetPreSignedURL(request);
// KLUDGE: remove duplicate domain name.
url = url.Replace(bucketName + "." + bucketName, bucketName);
This yields a proper working pre-signed URL for me (i.e. http://foo.example.com/myfile.txt?[...]) by working around the encountered limitation regarding the desired approach outlined below.
Justification
Manipulating the generated URL like so seems odd, but this not having an effect on the query string authentication is in line with how these signatures are created, see Query String Request Authentication Alternative, where you'll find the pseudo-grammar that illustrates the query string request authentication method:
StringToSign = HTTP-VERB + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Expires + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
That is, the domain name isn't used for the signature creation at all, rather only information regarding the resource itself; section Example Query String Request Authentication right below the referenced pseudo-grammar fragment illustrates this with an actual resource.
Assessment
I don't know whether there is still a misunderstanding on our part or whether this might just be a bug in the AWS SDK for .NET, see e.g. Why is my S3 pre-signed request invalid when I set a response header override that contains a “+”? for a related bug resolved via a similar workaround as well, which has meanwhile been fixed though; accordingly, this should likely be escalated to the AWS forums and/or support channels to get an appropriate answer or solution.
Good luck!
Desired answer [dysfunctional]
The S3 CNAME handling implies the bucket name already, so all you need to do is removing your bucket name from GetPreSignedUrlRequest, i.e. it should look like so:
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
I've tested this with a bucket of mine and it works as expected like so.
the presignedURL returns an URL object after signing the request. I have used the same and >dont have real issues, but there are some things to consider:
Ensure the object URL you are considering does not have a '//' it could easily happen if >you start the storage path starts with a "/", you would have stored the object in a path some >thing like https:///x/y/z/abc.png the key for such a resource is x/y/z/abc.png >and not /x/y/z/abc.png
If the above is ensured, then from the URL object that is returned get the query parameters >from the URL object url.getQuery() will return the query parameters which contains the >signature information, just suffix this with your original awsURL and things should work with >out any encoding issues.
Hope this helps..
Essentially you need to use url.getQuery on the returned url object rather than simply affixing it to the end of your bucket.
https://forums.aws.amazon.com/thread.jspa?threadID=70521

How can I validate OpenId token in C#?

I am trying to validate using this parameters:
"openid.mode=check_authentication"<br>
+ "&openid.assoc_handle=" + txtAssocHandle.Text<br>
+ "&openid.response_nonce=" + HttpUtility.UrlEncode(txtNonce.Text)<br>
+ "&openid.op_endpoint=" + txtEndpoint.Text<br>
+ "&openid.sig=" + txtSignature.Text<br>
+ "&openid.signed=mode,identity,return_to";
and it returns
is_valid:false
ns:http://specs.openid.net/auth/2.0
what am I doing wrong here?
the txt fields are being filled with login response values
Your openid.signed argument needs to be exactly what the OP sent to your RP rather than this incomplete hard-coded list of 3 parameters, for one thing. All your arguments should be URL encoded as well, not just your nonce.
There is a lot more to validating an OpenID token than just sending it back to the OP using "dumb mode". What are you trying to do?
Have you considered using an OpenID library? Seriously, getting OpenID right (meaning secure, and interoperable) is a big job. Way bigger than assembling just the right query string. :)

Asp.Net Absolute Path of a URL

To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :
HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;
It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.
Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.
Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.
I have used this in the past:
// Gets the base url in the following format:
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme
+ "://"
+ HttpContext.Current.Request.Url.Authority
+ HttpContext.Current.Request.ApplicationPath;
Old post but here is another slightly less verbose method
var baseUri = new Uri(HttpContext.Current.Request.Url, "/");
Using string interpolation:
string redirectUri = $"{this.Request.Url.Scheme}://{this.Request.Url.Authority}{this.Request.ApplicationPath}account/signedout";
Substitute 'this' for 'HttpContext' or 'HttpContext.Current' based on context.
I have used following and it worked for me both client and the server.
string surl = string.Format("{0}://{1}",
HttpContext.Current.Request.Url.Scheme,
HttpContext.Current.Request.Url.Authority);
Code :
string loginUrl = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/") + "Login/Login.aspx?UserName=" + LoggedinUser["UserName"] + "&Password=" + LoggedinUser["Password"];

Categories

Resources