Accessing OneDrive from Desktop App - c#

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.

Related

New Server Security Causing Issues To API Response

one of my old project/app was working fine for years, very recently client report that app does not working any longer due to API response issue.
it's just a get request to an API with some parameters..
till date (before issues occurs) it returns following response:
,,3,1669179307,0,
but recently it shows following response: (note nothing is changed in the source php/code files since project start)
<html><title>You are being redirected...</title>
<noscript>Javascript is required. Please enable javascript before you are allowed to see this page.</noscript>
<script>var s={},u,c,U,r,i,l=0,a,e=eval,w=String.fromCharCode,sucuri_cloudproxy_js='',S='bT0nP2RUNCcuc3Vic3RyKDMsIDEpICsgJycgKyAKJz9iVGYnLnN1YnN0cigzLCAxKSArICc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BdCgwKSAgKydvJysneHN1Y3VyJy5jaGFyQXQoMCkrICd5Jysnc3VjdXJfJy5jaGFyQXQoNSkgKyAnc3V1Jy5jaGFyQXQoMikrJ3UnKydpJysnJysnZHN1Y3VyJy5jaGFyQXQoMCkrICdfc3UnLmNoYXJBdCgwKSArJzQnKycnKydzdWN1cmMnLmNoYXJBdCg1KSArICc2c3VjJy5jaGFyQXQoMCkrICcwc3VjdXInLmNoYXJBdCgwKSsgJ3N1Y3VyaTUnLmNoYXJBdCg2KSsnc3U0Jy5jaGFyQXQoMikrJ3N1Y3VyNCcuY2hhckF0KDUpICsgJ2YnKycyc3VjdXJpJy5jaGFyQXQoMCkgKyAiPSIgKyBtICsgJztwYXRoPS87bWF4LWFnZT04NjQwMCc7IGxvY2F0aW9uLnJlbG9hZCgpOw==';L=S.length;U=0;r='';var A='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(u=0;u<64;u++){s[A.charAt(u)]=u;}for(i=0;i<L;i++){c=s[S.charAt(i)];U=(U<<6)+c;l+=6;while(l>=8){((a=(U>>>(l-=8))&0xff)||(i<(L-2)))&&(r+=w(a));}}e(r);</script></html>
here is curl screenshot:
And here is the postman screenshot:
and when i check the URL in browser it shows the expected result, though when i check the devtool (network tab), it looks like page is loaded two times.. 1st one provide error (HTML/js) response (read marked) 2nd one provide the expected response (green marked), so, it looks like when it's called directly by curl/postman/c#... fails.. but as browser can do redirect it passed.
here is the browser screenshot:
i am sorry, i added several screenshot to give better idea what is happening.
and here is the URL in question:
https://simpleclienttracking.com/membershipmanager/remotelogvisit.php?locID=1&orgID=1&deptID=1&barcode=8346420
now my question, is how can i use the API code/file to get the direct response as i was getting earlier? do i need to pass any header? update/modify server htaccess file or what?
To test the error in deep, i have tried another URL from another hosting provider, in that case i am passing post request to an URL, and this server response slightly different thing, but looks like core is same, redirect!
here is the response from new/another server:
<script>document.cookie = "humans_21909=1"; document.location.reload(true)</script>
so, it's looks like hosting providers has applied some kind of security for direct URL access?
thanks in advance for any upcoming help
best regards

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

POST to /likes only works after GET - bug or by design?

My app has permissions to "like" something on FB on a user's behalf. Using the Facebook C# SDK (5.4.1), here's what I wrote:
Facebook.FacebookClient fb = new Facebook.FacebookClient(AccessToken);
object o = fb.Get("1234567890_12345678901234567/likes");
dynamic parameters = new ExpandoObject();
dynamic success = fb.Post("1234567890_12345678901234567/likes", parameters);
The second line is superfluous and creates an unnecessary round-trip, as we're not interested in the other "likes" on the same object. However, without it, fb.Post fails and throws "The remote server returned an error: (400) Bad Request."
Is this a bug in the C# SDK, or a bug in the graph API, or is it by design?
Note that it's possible to POST to /comments without a previous GET.
Yes, it should be possible to do post commands without a get. Strangely enough, my like code with the 5.4.1 does not require the extra GET directly before the POST for doing a like. Maybe somewhere else in my app's flow I've already done some sort of GET via the API. However, I'm going to investigate my DELETE problem with me/permissions that I'm encountering (http://stackoverflow.com/questions/8598614/facebook-c-sharp-api-return-400-when-deauthorizing-app) and see if a get to the me/permissions first will help resolve that issue.

OAuth Test Console signature doesn't agree with working request

I'm having trouble using the LinkedIn API due to being returned a 401 with auth_problem=signature_invalid. I do however have a project which seems to be working with fine so I'm using this to identify the differences.
I read that I can debug with the OAuthTestConsole however this appears to be generating a different signature than the working project.
Since I'm this is only a hobby you can have both my keys:
API Key: gh69xphn2hcr
Secret Key: 0ld6NVvjmpvrmZqw
My working request is:
POST https://api.linkedin.com/uas/oauth/requestToken HTTP/1.1
Content-Type: application/x-www-form-urlencoded Host: api.linkedin.com
Content-Length: 175
Connection: Keep-Alive
oauth_consumer_key=gh69xphn2hcr&oauth_nonce=186481&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1325243837&oauth_version=1.0&oauth_signature=gTeEgzknW6DyI3aFTDcXduroIG4%3d
However the oAuthTestConsole returns an oauth_signature of WNcZFXAC5Y2hoK4srFiFc69zi0M= which is nothing alike (encoded or not).
I'm thinking I must be using the TestConsole wrong and this is preventing me from fixing my issue between the working / non working projects. Could you please point me in the right direction as to why this might occur?
To use the OAuth Test Console, you need to make sure that all of the parameters are exactly the same
- the timestamp (you'll need to set that manually, as it'll otherwise be created based on the current time)
- the nonce (check to see what your library is sending)
- the method (POST in this case)
You need to clear both fields for the access_token (since you don't have one for this initial request)
There is a working C# example posted by a community member here:
https://developer.linkedin.com/thread/1190
Many people have had a lot of luck starting with that, as using OAuth can be tricky without an example to start from.

Categories