I have one API and two different domain. How can I check which domain host triggered api request?
Example:
API: example.API.com
Domain1: example.Domain1.com
Domain2: example.Domain2.com
and I want to know which domain call my API?
I used C# for my code, maybe there is a ready way to solve my problem but if not then maybe some advice on how to approach the problem?
I try code.
string host = _httpContextAccessor.HttpContext?.Request.Headers.Referer.FirstOrDefault();
This code gives me the full url of the client, but I don't know if that's a good way because
this can be null.
Related
I'm working on integrating with the Azure Batch API and construct a client object based on credentials I pass through. What I want to know is how can I test to see whether the connection is valid and the credentials are correct? I can't see anything on the API to do this. You can just create the BatchClient object and then call operations on it to list jobs, pools etc, all of which fail with a complex error if your initial credentials were wrong. I want to be able to test for incorrect credentials before I attempt any other operations. Does anyone know how to do this?
var client = BatchClient.Open(new BatchSharedKeyCredentials(
string.Format("https://{0}.{1}.batch.azure.com",
_primaryBatchAccountName,
_primaryRegion),
_primaryBatchAccountName,
_primaryBatchAccountKey));
This is the code to create the client object. But it doesn't throw any error even if you pass it completely wrong values. You only get the error when you try and do anything with it.
The BatchClient doesn't keep a persistent connection "open." It just issues REST requests to the target endpoint whenever required (i.e. when you use a method).
To the best of my knowledge, there is no way to determine if you have the "right" credentials values or endpoint data until you try to use the BatchClient to actually communicate with the server. This is because it's not really possible for the client to know what endpoints are valid, nor is it possible for it to know what a "valid" credential looks like, or if the credential you specified is correct (the server must verify that).
The best recommendation I can come up with is to just try to issue a simple API call (like a ListJobs or something) and ensure that it completes successfully. That should validate that your BatchClient is working.
I'm coming to .net web api from a JavaScript background, and I'm trying to make a proxy to help with a cross domain JSON request. I'm GETing from a server I don't control the source code for, so I can't configure CORS directly. Likewise, it doesn't speak JSONP.
So two questions as I try to get my head around Web API:
1) Is Httpclient the right tool for this job? (if not, what is?)
2) If httpclient IS the right tool, what is an absolute bare bones httpclient config so I can test this out? Not worried about throwing exceptions or anything else other than just GETing API data and feeding it to a jQuery client.
I guess one other piece of information that would be nice would be building username / password authentication into the http request.
Any help is much appreciated, as are links to any good blogs / tutorials / etc that might help as an introduction to this sort of thing. I've watched several today alone, and I'm still not able to get a basic http request going on the server side without resorting to cutting / pasting other people's code.
Thanks in advance!
** EDIT - To make this question a bit more clear, what I'm trying to test is 1) Can the proxy connect to the third party server, which involves authentication via a username and password 2) Can the proxy then respond to the jQuery client request with the JSON data it received from the third party server.
Thanks to all who have taken the time to respond.
HttpClient seems to be ok in this job.
About the minimal config- it depends on what the third party expects. In most cases would work out-of-the-box, but there always may be some minor tweaks like headers and/or auth code.
I have just found some blog entry where some author shows how to test such a proxy and shows the proxy code too. Please see: http://www.davidbreyer.com/programming/2014/10/11/create-fake-responses-to-rest-service-calls-in-c/
You can find info about sending credentials here: How to use credentials in HttpClient in c#?
HTH
EDIT:
this sample code should work (copied from blog above and modified):
public class Proxy
{
public async Task<ExampleDto> GetExample(int id)
{
var client=new HttpClient();
//set some auth here
//set other headers
var response = client.GetAsync(
string.Format("/api/restserviceexample/{0}", id))
.Result.Content.ReadAsAsync<ExampleDto>();
return await response;
}
}
It's so simple that you can just run it and see if the other server responds. If not, you can play with headers - since all the session info and user auth info are sent using ookies and/or headers, all you have to do is to see how it's made with regular browser and then fake it on the server. Probably best tool for this job will be Fiddler.
However - there is one thing to consider. If the other service has special method for authorization (other than passing credentials with each request) the whole thing becomes tricky, since your proxy should perform authorization using their service, then store their auth cookie on the server or propagate them to the browser and attach them with all next requests.
First, you don't need ASP.NET with C# if you really want minimal.
.NET has great http handling without ASP. Check out classes like HttpListener, HttpListenerContext, HttpListenerRequest, etc... Yes, you'll have to write some boilerplate as your application, but these classes are pretty good.
See among others:
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=599978
Second, if you want user & password, I'd checkout using oauth authentication so you don't have to deal with them directly. Google Plus, Windows Live, Facebook, etc... all have similar OAuth 2.0 APIs for that. See among others:
http://msdn.microsoft.com/en-us/library/dn659750.aspx
https://developers.google.com/+/web/signin/server-side-flow
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2
I'm using (with satisfaction) some web services from an Android application.
I use https (I bought a SSL certificate).
I want to prevent unwanted accesses from others that know the urls of my web services.
I use a "secret key" that the app must provide to the web service method, but it's stored in a constant variable inside the code and I know this is not the best solution to ensure security.
Android web service call (using ksoap):
try {
SoapObject request = new SoapObject(configuration.getNamespace(), methodName);
request.addProperty("securityKey", SECURITY_KEY);
C# web service
[WebMethod]
public string UserRegistraion(string securityKey, string data)
{
if (securityKey != Environment.SecurityKey)
{
return "WRONG_KEY";
}
What's the best way to achieve the definitive solution?
EDIT:
As someone suggested, I asked the same question also on security.stackexchange.com
https://security.stackexchange.com/questions/30850/web-services-how-prevent-illegal-accesses
You simply can't do this. You should obfuscate your code. This is an old battle of software developers vs. crackers
You can't block someone on using/analyzing a code that resides on the client-side, but you can make it difficult in a point that almost all people will give up on doing it because it is too much hard to exploit your code.
I have a WCF REST-service that is used by a mobile application used in different countries. It's accepting and returning JSON, and I use StructureMap.
The idea is to create one service instance for all countries, but I need to know what country is calling the service and do some logic on that in the service (for example, determine the connection string to be used).
however, I want to avoid that country code has to be passed with each service request. What are my options here?
Can I, for example, have one endpoint for each country? But in that case, how can I know what endpoint/country code was used to call the service?
Maybe other possibilities?
Multiple endpoints could be a solution, but you need a reliant way of determining which endpoint was actually used. Given the "disconnected" nature of WCF REST services (by that I mean the usage of non WCF types to do the communication and just using the WCF attributes), this would require you to write a WebHostFactory that specifies the country on creation of the service for a given endpoint. What you could to is inspect the WebOperationCurrent.Current instance to get access to information hidden from your method signature. For example:
Uri requestRoot = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri;
if (requestRoot.PathAndQuery.Contains("en-us")) {
// use english locale
}
else if (requestRoot.PathAndQuery.Contains("de-de")) {
// use german locale
}
You would need a better strategy to determine the actual country/language, but the basic idea is to re-host the same service under multiple paths and inspect those paths within the request using the current WebOperationContext instance.
Edit
From the comments above, I would like to add that you have access to the UserAgent string for the current request using the WebOperationContext. So you could also inspect those information looking for a clue about the requested language. But keep in mind that those "implicit" information are only clues but never clear indications about what the user wants.
I'm working on a real estate website. It would be ideal to have my client's featured properties have their own unique URL like:
www.realestatewebsite.com/featured/123-fake-st/
I'm constructing a CMS for my client so that they can add/delete featured properties in an admin backend, meaning that I need to write a program to automatically add the new URL for them based on the address they input in the database through the CMS.
I'm new to URL Rewrite. What would be the best way to go about this? I've considered using RewriterConfig in the web.config, but then I'm worried I would encounter problems writing a program that adds new rules to the web.config file. I thought about using a regex expression in the RewriterRule to find anything after /featured/ in the URL, but then if I'm just using the address in the LookFor then how would it know which property ID to use in the SendTo?
It would be ideal if I could just have a file put the address after "/featured/" into a string, look in the database for the address and retrieve the Property ID and then redirect the users that way.
As I said, I'm new to URL Rewriting and it would be great if someone could point me in the right direction.
Thanks!
-Aaron
There are different ways of doing this. Common to all solutions are the following:
Set up a algorithm to create the URIs and store them in the database (changing space to - is a simple way to achieve this.
Route the URI by making the address string into a parameter
Routing can be done a variety of ways.
If you have control of the server, or they have control of the server, you have the ability to set up IIS rewriting on the IIS instance on their server (good starter URI).
If this is hosted on an ISP, you may not have this option and have to use IIS rewriting and will have to use ASP.NET routing. Here is a good article to start with to undestand this. If you are using MVC, the routing is "built in".
I would suggest using URL Rewrite Module for IIS7, look here:
http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/