http headers for c# client to Java Service - c#

Hi ive been trying to add http headers to a webclient in c# , ive been looking alot of places and have had little luck often people point to a Credentials class however i only have ClientCredentials my client also missing is a PreAuthenticate field?
The service is written in Java and I can add http headers to that as follows
reqHeaders.put(HEADER_NAME_USERNAME, Collections.singletonList(USER_NAME));
reqHeaders.put(HEADER_NAME_PASSWORD, Collections.singletonList(PASSWORD));
((BindingProvider) webWS).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,reqHeaders);
However i have no idea how to do this in c# ive tried endpoint address builder, ClientCredential, windows.ClientCredential basically anywehre i can find a username and passsword
When i make a request in java i capture the http packet in wireshark
looks kinds like this
+hypertext transfer protocol
+POST
post stuff
Password: mypass
Username: username
soapaction: ... and so on
i cant change the server side code all i know is if i can add two headers one called username and one password with values ill be Sheening (read:winning)

http://msmvps.com/blogs/paulomorgado/archive/2007/04/27/wcf-building-an-http-user-agent-message-inspector.aspx
This mostly answered my problem, instead of editing the app.config though i jsut added the newly defined behaviour class under
webservice.Endpoint.Behaviors.add(new CustomBehavior(params));

Related

How to add custom http header to google big query client in c#

I am trying to add a custom header to google bigquery client in below way, some reasons it is not working. Can someone suggest me how I can add custom header to google bigquery client.
Below is my sample code:
var gClient = BigQueryClient.Create(projectId, credential);
gClient.Service.HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("test", "this is default header");
var results = gClient.ExecuteQuery(query, null);
With above code, I can see that the custom header 'test' is added to the httpclient, but when gClient executes the query, I don't see this custom header.
I am using the fiddler to monitor the traffic from my machine. In fiddler, the I can see that there are two calls are made.
i. oauth authentication
ii. bigquery execution
In both of the messages I dont see the default http header 'test'.
I also tried, gClient.Service.HttpClientInitializer.Initialize() to initialize the httpclient, but didnt work.
var gClient = BigQueryClient.Create(projectId, credential);
ConfigurableHttpClient httpClient = new ConfigurableHttpClient(new ConfigurableMessageHandler(new CustomMessageHandler()), true);
httpClient.DefaultRequestHeaders.Add("xxxxx", "yyyyyyy");
gClient.Service.HttpClientInitializer.Initialize(httpClient);
In this case also, it is same problem... the default header is not part of the httprequest.
Can someone help me to solve this issue...?
FYI... we are intercepting all outbound calls using a proxy and based on this custom http header we need to take decision whether to allow outbound call or not. So, we would like to inject it at the service side and verify this custom header in the proxy.
As explained above, I have tried adding the DefaultRequestHeaders to the httpclient, but it is not working.
Also, I have tried httpclient.MessageHandler.AddExecuteInterceptor(). but still didnt work.
My question... can we inject a default httpclient for all outbound calls in c#? especially for google big queries.

Accessing OneDrive from Desktop App

I'm trying to get to grips with OneDrive, using this tutorial:
https://msdn.microsoft.com/en-us/library/hh826529.aspx
When I run in code, it gets as far as the makeAccessTokenRequest function, sending the following requestURL:
"https: //login.live.com/oauth20_token.srf?client_id=[myclientID] &client_secret=[myclientsecret]&redirect_uri=https:// login.live.com/oauth20_desktop.srf&grant_type=authorization_code&code=[authcode]"
(please ignore the spaces after "https:", I had to add them here to allow the question)
[myclientid], [myclientsecret], and [authcode] all appear to be populated correctly. It seems to get a response, as it runs the function "accessToken_DownloadStringCompleted", but throws a "TargetInvocationException" error, The inner message of the error is ""The remote server returned an error: (400) Bad Request.".
Could anyone throw any light on this? I'm completely new to this, so apologies if my question makes no sense, or is irritatingly vague..
Requests to the oauth20_token.srf end point need to be a POST with the parameters in the body of the post, instead of the query string. Since you didn't mention what code you're using to build the HTTP request it's hard to provide an example, but take a look at RedeemAuthorizationCodeAsync in my sample OAuth 2 project for an idea.
The outgoing request should look like this:
POST https://login.live.com/oauth20_token.srf
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}&grant_type=authorization_code
You may also find this tutorial easier to follow than the one you linked with: https://dev.onedrive.com/auth/msa_oauth.htm.
If you are doing something with OneDrive (you tagged the post OneDrive) then you may want to consider using the OneDrive SDK instead. It includes authentication for several types of .NET projects so you don't need to figure out how to do auth yourself.

Sending Http requests from a webbrowser to HttpListener

I've set up an HttpListener running on port 8086 on my custom server application, which works with JSON and XML over sockets. I can't change my server application to any other implementation, I am stuck with it for now.
I'm a bit new to Http, so feel free to correct my naviety below! I've searched, but can't find anything that deals with my exact problem.
When I use Hurl.it to send an HttpRequest to the server, the GetContext function fires no problem and I am able to send an html response back to Hurl.it.
Now, the question is, I want to be able to send out Reset Password email links in the form of "http://myip:PORT/resetpasswordseed=74283235" and have a browser be able to receive, parse and display a dynamically generated html form. (I will also need to add SSL to this a bit later, as I don't want a newly updated password being sent as plain text in a URL.)
Now, when I click the URL link http://myserverip:port/resetpassword with Edge or Firefox the GetContext function does not fire and the web browser times out. Have I missed something or am I trying to do something that is not possible? I don't get an error message or an exception or anything.
Any help would be appreciated.
Cheers
Craig.

What is an absolute bare bones httpclient configuration?

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

How to use Yahoo REST Api in C#

I'm just trying to make an yahoo boot that send to registered user of my application an instant message. I've spent some hours searching the web on how to do it but yahoo developer documentation sucks.First of all I don't know what servers I should use for authorization, log in, and messaging. I have a consumer key and I've tried to follow this steps but nothing works.
Any advice/suggestion is welcome.
The documentation looks to be very good, I think the issue here is that your knowledge of how REST API's work in general is a bit lacking.
Let's talk about diagram #2: Get a request token using: get_request_token.
get_request_token is part of an HTTP endpoint, and in their diagram they want you to pass in a handful of parameters to validate your request.
oauth_consumer_key
oauth_nonce
oauth_signature_method
etc
(If you need more clarification of any step you can find it in the tree view on the left hand side of the page)
The request URL:
https://api.login.yahoo.com/oauth/v2/get_request_token.
Now at this point you can either use the HTTP GET or POST verb. If you decide to use GET you will need to include those above parameters as a query string.
?oath_consumer_key=myConsumerKey&oauth_nonce=oathNonce etc
I will leave it to you to write the associated C# code. You'll want to start off with the HttpWebRequest.Create() method

Categories