IncomingWebRequestContext.UriTemplateMatch null in WCF Service - wcf

I am trying to implement OAuth in a web service such as:
http://www.codeproject.com/Tips/372422/Secure-WCF-RESTful-service-using-OAUTH
Each time, when the Authenticate method is fire, WebOperationContext.Current.IncomingRequest exists, but UriTemplateMatch is null. This is even the case when using the WCF Test Client, so my client app isn't the problem. Ultimately, I need to access the QueryParameters under UriTemplateMatch.
In the Authenticate method, this is where the code breaks:
NameValueCollection pa = context.UriTemplateMatch.QueryParameters;
Looking for a different solution than this so everything is processed in one request:
https://stackoverflow.com/questions/7344478/using-the-wcf-http-web-api-uritemplatematch-is-always-null
Also, just as much as a solution, I am looking for a reason why the UriTemplateMatch would be null only in the case of a WCF Service. There are hundreds of articles on the presence of this problem, but I haven't found a good solution and/or explanation. I think I may be missing something in my web.config.

It seems that this solution is expecting incoming calls like :
http://localhost:49262/TestProject/Service.svc/user/123?oauth_consumer_key=key&oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&oauth_signature=cUobFDxVB5wjPe9X2XICJ6awmnE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1289976718&oauth_version=1.0
There are two ways to attach oauth parameters, one is through headers, another is through query string, both are valid, so I choose to attach oauth parameters in query string. There is not any problem to retrieve them from IncomingWebRequestContext.Headers if those oauth parameters are in headers
This solution is not from me. Check this link.

Related

Variable scope in Apigee Edge. Request and Response

I am working with Apigee edge lately and am having trouble with a specific implementation. Essentially, the client will request an oauth token from their API through apigee. However, to make calls to our proxy they need an oauth token from us as well. So far my flow goes like this.
Client calls token endpoint on apigees side, a service callout is made to get a token from one of our other proxies (returned as a json object). Then the request passes through and gets the token from the clients API.
Here is where I am having trouble. After the response from the clients API, I want to use the assign message policy to modify the response to include the first token that was grabbed from our other proxy. The problem is the variable seems to be falling out of scope between request/response.
Am I missing something obvious here? I have looked into the PopulateCache policy, but I feel like this may be overkill as I only want the variable to remain in scope for the request/response. Thanks for any clarity you guys can provide! Sorry if my explanation is not very good, I am VERY new to Apigee Edge.
You aren't missing anything obvious. Variables should not fall out of scope between request and response flows. You are right that PopulateCache isn't necessary.
One item that catches people sometimes is how you access the response from the service callout. If you configure the service callout response to be stored in a variable called calloutResponse, then when you access the body to extract information, you'd use calloutResponse.content as the source. If you try to access calloutResponse instead, you might think that the variable had disappeared.
Add more details/trace if that is not the problem, and we can figure out what is going wrong.

Submit status to web services dynamically without having any prior knowledge of them

I'm developing a WCF SOAP web service based on this schema.
Basically it takes product orders from many clients.
As part of the submit operation the client is allowed to provide a URL where it expects asynchronous status updates on the order and it's line items.
I want to know if anyone has experience with a similar architecture? How did you go about implementing this?
Can i use a dynamic web reference as stated here? I would think this won't work very well in this situation. I'm pretty sure i'll need Chuck Norris to handle all the exceptions that get throw at the presence of any client service that is not identical or slightly different... even if it does pass schema validation.
The best thing i can think of is building the status object, serializing it into the SubmitResponse request soap message xml then sending it off using curl. something like:
curl -d "<my soap message xml>" "http://www.example.com/target"
Any ideas?
Question FOCUS
The problem i'm trying to solve is how to submit status responses to web service urls dynamically without having any prior knowledge of them.

WCF Rest - what are the best practices?

Just started my first WCF rest project and would like some help on what are the best practices for using REST.
I have seen a number of tutorials and there seems to be a number of ways to do things...for example if doing a POST, I have seen some tutorials which are setting HttpStatusCodes (OK/Errors etc), and other tutorials where they are just returning strings which contain result of the operation.
At the end of the day, there are 4 operations and surely there must be a guide that says if you are doing a GET, do it this way, etc and with a POST, do this...
Any help would be appreciated.
JD
UPDDATE
Use ASP.NET Web API.
OK I left the comment REST best practices: dont use WCF REST. Just avoid it like a plague and I feel like I have to explain it.
One of the fundamental flaws of the WCF is that it is concerned only with the Payload. For example Foo and Bar are the payloads here.
[OperationContract]
public Foo Do(Bar bar)
{
...
}
This is one of the tenants of WCF so that no matter what the transport is, we get the payload over to you.
But what it ignore is the context/envelope of the call which in many cases transport specific - so a lot of the context get's lost. In fact, HTTP's power lies in its context not payload and back in the earlier versions of WCF, there was no way to get the client's IP Address in netTcpBinding and WCF team were adamant that they cannot provide it. I cannot find the page now but remember reading the comments and the MS guys just said this is not supported.
Using WCF REST, you lose the flexibility of HTTP in expressing yourself clearly (and they had to budge it later) in terms of:
HTTP Status code
HTTP media types
ETag, ...
The new Web API, Glenn Block is working addresses this issue by encapsulating the payload in the context:
public HttpResponse<Foo> Do(HttpRequest<Bar> bar) // PSEUDOCODE
{
...
}
But to my test this is not perfect and I personally prefer to use frameworks such as Nancy or even plain ASP NET MVC to expose web API.
There are some basic rules when using the different HTTP verbs that come from the HTTP specification
GET: This is a pure read operation. Invocation must not cause state change in the service. The response to a GET may be delivered from cache (local, proxy, etc) depending on caching headers
DELETE: Used to delete a resource
There is sometimes some confusion around PUT and POST - which should be used when? To answer that you have to consider idempotency - whether the operation can be repeated without affecting service state - so for example setting a customer's name to a value can be repeated multiple times without further state change; however, if I am incrementing a customer's bank balance this cannot be safely be repeated without further state change on the service. The first is said to be idempotent the second is not
PUT: Non-delete state changes that are idempotent
POST: Non-delete state changes that are not idempotent
REST embraces HTTP - therefore failures should be communicated using HTTP status codes. 200 for success, 201 for creation and the service should return a URI for the new resource using the HTTP location header, 4xx are failures due to the nature of the client request (so can be fixed by the client changing what they are doing), 5xx are server errors that can only be resolved server side
There's something missing here that needs to be said.
WCF Rest may not be able to provide all functionality of REST protocol, but it is able to facilitate REST protocol for existing WCF services. So if you decide to provide some sort of REST support on top of the current SOAP/Named pipe protocol, it's the way to go if the ROI is low.
Hand rolling full blown REST protocol maybe ideal, but not always economical. In 90% of my projects, REST api is an afterthought. Wcf comes in quite handy in that regard.

WCF and UserName credentials when using basicHttpBinding

As far as I know, in order to use UserName credentials with basicHttpBinding to authenticate against the SQL Server membership provider, I need to set TransportWithMessageCredentials security mode. But recently I had a look at the WCF Security guide. And in this book I found the similar example, but instead of TransportWithMessageCredentials, Basic mode is used and a custom HTTP module is created that will authenticate users.
I'm wondering which approach is worth using?
Both approaches do the same but they use different approach. The first approach uses SOAP header to pass credentials whereas second approach uses HTTP header to pass credentials.
The second approach involves additional network roundtrip (handled internally by WCF) because first call is rejected with 401 status code and demanded Basic authentication and only second call contains the header with credentials. This is the way how HTTP authentication works and client should not send credentials until server requires them (even there is possibility to preauthenticate but I think WCF doesn't use it). The second approach cannot be used with streamed transfer mode.
There can be one additional difference between those two methods. The first approach authenticate each call whereas second approach authenticate connection so if you call the service multiple times from the same proxy (and the same connection) you will be authenticated only once with the second approach but for each call with the first approach.
Edit:
There is no preference between those two. You will use the one which is more suitable for your needs. If you have control over both client and server or if you know that client will use some more powerful SOAP stack the first one is easier to set up. If you don't have control over your clients and they can use different platforms you can find second more interoperable.
As a side note the first one works only with SOAP protocol whereas the second one works for SOAP, POX and REST (POX and REST require different binding).

Restrict methods of a WCF service from unauthorized (unwanted) user access

I'm wondering how I can restrict some methods from unauthorized user access. Let's assume I have a WCF service with the following contract:
int Login(string username, string password);
Invoice[] GetCustomersInvoices(int customerId);
A user should act in the following way:
Login to verify against the service and get his custumerId
fetch his invoices by invoking the corresponding method with his customerId
Well, that's maybe a stupid question, but what if customerA's id is 23, but somehow customerA knows customerB's id, which is 42. Now customerA could read customerB's secret invoice data...
What could I best do to avoid this?
You shouldn't use a single id for identifying someone. There are many ways of enabling authn/authz in WCF, I like the article at http://msdn.microsoft.com/en-us/magazine/cc948343.aspx for a good introduction on some ways of doing it.
Your current approach of calling methods will only work if you are able to implement secure(persistent) channel between client and server using SSL or any other such mode (typical scenario would be Baking Payments Getaways)
So IMO you need to implement your user authentication inside the method (no separate calls). i.e. you have to pass userid and password along with invoiceid to GetCustomersInvoices() method and inside it you need to authenticate the user and retrieve the data.
Following would be solution for such scenario,
Implement your own User Name Password Validations (custom usernameathentication), which will first authenticate the user and than it will call the method given. Since this will happen in one request so it will solve your problem.
Typical service method call would be like,
Service.UserName = "abc"
Service.Password = "***"
Service.GetInvoiceDetails(1233)
You can get the use of Message Headers and Body to pass your custom values, Webservices support such scenario where you can pass encrypted data in SOAP headers.
Alternatively you can use Certificates also, but these are not free.
In general you can go through following links to get more info in various kinds of security WCF supports,
http://msdn.microsoft.com/en-us/library/ms731925.aspx