Dwolla oauth access token in windows app - c#

I am creating a windows 8 metro app but I am having trouble with getting the oauth2 access token. I can get the temporary code with this code just fine:
Uri requestUri = new Uri(string.Format(AUTH_URL + "?client_id={0}&response_type=code&scope={1}&client_secret={2}&redirect_uri={3}", CLIENT_ID, string.Join("|", scopeList.ToArray()), CLIENT_SECRET, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri));
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri);
But when I try to use that code to get the permanent access token, it either gives me an Internal Server Error (500) or times out. It gives me a 500 when I don't have a redirect_uri, so I keep it in. Otherwise my request just times out with no response with this code:
private const string TOKEN_URL = "https://www.dwolla.com/oauth/v2/token";
Uri requestUri = new Uri(string.Format(TOKEN_URL + "?client_id={0}&client_secret={1}&grant_type={2}&code={3}&redirect_uri={4}", CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, code, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri)));
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.SilentMode, requestUri);
All of my strings are uri escaped. I just don't know what I am doing wrong.
Using anything besides the WebAuthenticationOptions.SilentMode option just shows a loading browser window
Also I can't use OAuth libraries that are made for C# because they use .NetFramework while Windows 8 Apps use .NetCore, a trimmed down version.
Any help would be great

The requestUri looks different between the temporary code and the redirect permananent access token. It needs to be the exact same thing.

Related

LinkedIn access token api returns bad request error in c#

I am using linked oauth 2 api to fetch the access token.But I am getting a 400 (BadRequest) response from that api.I am sharing the code below
NameValueCollection parameters = new NameValueCollection();
parameters.Add("grant_type", "authorization_code");
parameters.Add("code", Code);
parameters.Add("redirect_uri", RedirectURL);
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType]="application/x-www-form-urlencoded";
var result = client.UploadValues("https://www.linkedin.com/oauth/v2/accessToken", parameters);
Could anyone help me to find what went wrong here. I am passing the correct values for all parameters, got client_id, client_secret from my application and the code I am getting from my initial authorization request.
I am not able to test this scenario in postman since the auth-token request depends on the code generated from the authorization step.
AuthorizationUrl must look like this
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=78y4rii84jcf43&state=E30980C1T666444z&redirect_uri=https://www.testWeb.com
Access Token Url will look like this,
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=AQTTP5DZ68JHRVO2_i9vpie8KBZ3gfgffhjfhjfhjfp88hf3szNauFkUpuvqfyKhjsmO7Bcps4JXUo1EWQay1q1q1MXKsajRWoZ4q-ofmTjJfknaYTk5SO5oHUgfhgfdsgfdgdfdgfsgdgdhgdhgddipkfTIzdkGUSWZkPYS1&client_id=78y4rii465rv084&redirect_uri=https://www.testweb.com&client_secret=1t56E7bLDl2fnVWh
And your Params are missing with
QUESTION_MARK (?) after https://www.linkedin.com/oauth/v2/accessToken
your Grant type param must include grant_type=authorization_code
than & param
than client_id=YourApiKey
than & param
than redirect_uri=YourRedirectUri
than &
than client_secret=YourSecretKey

Azure Data Lake Store "The access token is not provided in the 'Authorization' header" using HttpClient

I'm having issues trying to access Azure Data Lake Store via the WebHDFS APIs using an HttpClient in .NET
This is my code:
using (var client = new HttpClient())
{
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, resourceUri);
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
message.Content = new StringContent(JsonConvert.SerializeObject(body));
message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await client.SendAsync(message);
var content = await result.Content.ReadAsStringAsync();
result.EnsureSuccessStatusCode();
}
Which returns me a 401 with this message: "The access token is not provided in the 'Authorization' header"
The weird thing is if I take the exact accessToken and resourceUri and put it in Postman it works fine (201).
I've added the application under Access control, and in the Data Explorer > Access tab, and have given full rights (Read, Write, Execute).
I even rewrote this using RestSharp yet the same error is given to me, I checked the JWT token it is definitely correct and returning data when I use it in Postman. It seems like the header is being stripped out somewhere.
This is driving me crazy, I can't figure out what I am doing wrong! Can anyone please help?
The issue seems to be related to a redirect that was happening that added an extra parameter added to the operation in the resource URI.
The parameter was "write=true". So I've updated the Resource URI to include the parameter.
i.e. for PUT operation "https://yourstore.azuredatalakestore.net/webhdfs/v1/xxx?op=CREATE&write=true"
Very weird behaviour but it works now.

Get And Use Facebook Access Token Without HTTPS

I have the following url for the first stage. getting code http://www.facebook.com/dialog/oauth?client_id=myappid&redirect_uri=myurl;state=e879888c-7090-4c09-98a5-ff361b30d55;scope=email
and
url = String.Format(#"http://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}",FacebookAppId, redirectUrl, FacebookSecret, code);
WebClient webClient = new WebClient();
var tokenVars = webClient.DownloadString(url);
var responseVars = HttpUtility.ParseQueryString(tokenVars);
string access_token = responseVars["access_token"];
string data = webClient.DownloadString(String.Format("http://graph.facebook.com/me?access_token={0}", access_token));
var jobject = JObject.Parse(data);
400 BAD REQUEST is returned.
Question: Is it possible to get facebook access token without connecting by http s ?
Question: Is it possible to use access_token without HTTPS? NOT HTTP
for a secure you must take https,
maybe if you aren't, some bad thing will show, #long process..
i just browse for your issue, and same thing

C# Network credentials not being passed to server?

Edit: Using:
byte[] authBytes = System.Text.Encoding.UTF8.GetBytes(user + ":" + password);
wr.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
Seems to work fine.
I have an application that communicates with a CMS. I'm currently trying to get this client to be able to upload text/xml data to the CMS using a "POST" method.
I can pass this through using curl perfectly fine:
curl -u user:password -H "Content-Type:text/xml" -d "<element>myXML</element>" serverURL
However, trying to use the HttpWebRequest in C# I can't get the server to return what I want it to. So I fired up Wireshark and had a look at what was actually being passed through, and it's pretty much identical except for the fact that when using curl I can see:
Authorization: Basic <a bunch of hex>=\r\n
Credentials: user:password
In the HTTP header fields, while in the output from my client, these header fields are simply not present. ("Credentials:" isn't actually there in plain text, it's a subtree of "Authorization:" - so I'm not sure where it's getting it from, but the username and password are correct.)
The C# code I'm trying to use to set the credentials for the webrequest is something like this:
NetworkCredential myCred = new NetworkCredential(
user, password, serverURL);
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(serverURL), "Basic", myCred);
HttpWebRequest wr = (HttpWebRequest) HttpWebRequest.Create(serverURL);
wr.Credentials = myCache;
I've tried just setting the credentials like this too (and without specifying serverURL):
wr.Credentials = new NetworkCredential(user,password,serverURL);
But that still doesn't make it show up in wireshark. Does anyone have any idea if:
A) That authorization information should actually be in the HTTP header for this to work, and
B) If it is - then how do I make C# put it in? I only seem to be able to find decent examples using the default credentials, which doesn't apply to what I'm doing.
Thanks in advance.
.NET's WebRequest has an infuriating default behavior where it only sends credentials after receiving an HTTP 401 Not Authorized response.
Manually adding the credentials header (as you've done) seems to be the best solution available.
More details in this post

Failing to retrieve access token in .NET desktop app

I'm writing a .NET app that runs on a Windows computer. It is not accessible through the browser. The problem is, I can't authenticate like I should. I'm currently coding in C# .NET, more specific in C#.
I have a webbrowser control on my form.
The user logs on to facebook through this webbrowser control.
After the logon, I start the authentication procedure.
I then retreive a code.
Here's where it goes wrong. With this code I want to obtain an access token.
The generated request URL looks like: https://graph.facebook.com/oauth/access_token?client_id=____MY_APP_ID______&redirect_uri=http://localhost/&client_secret=_____MY_APP_SECRET_____&code=____MY_RETREIVED_CODE_____ and is made through the code below.
Please note that my redirect URL is http://localhost. This should be okay, right?
Also, in my App Settings, I have the following information.
Site URL: http://localhost/
Site Domain: localhost
private String ExchangeCodeForToken(String code, Uri redirectUrl)
{
var TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token");
var url = TokenEndpoint + "?" +
"client_id=" + _AppID + "&" +
"redirect_uri=" + redirectUrl + "&" +
"client_secret=" + _AppSecret + "&" +
"code=" + code;
var request = WebRequest.CreateDefault(new Uri(url));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var responseReader = new StreamReader(responseStream))
{
var responseText = responseReader.ReadToEnd();
var token = responseText.Replace("access_token=", "");
return token;
}
}
}
}
When I execute this, I get this error:
error http://www.imageupload.org/getfile.php?id=50131&a=447f6fcc0ebd4d3f8e8a59a3a6e36ac3&t=4de0841c&o=0889D68FDC35508BA2C6F2689FCBAB7C30A8670CC9647EE598701D8BEC13ED278F0989D393&n=autherror.png&i=1
Webexception was unhandled by user code
The remote server returned an error: (400) Bad Request.
Here's where I think I might be going wrong:
Are my app settings correct?
Should my redirect url be http://localhost, even if there isn't actually a service listening there?
Most importantly:
how do I get rid of this error and retreive the access token?
Thanks in advance!
You get this error because you are not supposed to call this URL from a Desktop app : as far as I know, you can not use the token endpoint for Desktop app authentication. Also, you can get the access token directly (no need to ask for a code first). Here is what you have to do.
Load the following URL in your embedded web browser :
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&
redirect_uri=https://www.facebook.com/connect/login_success.html
The user will be asked to log in and will be redirected to this URL with the access token in the URL :
https://www.facebook.com/connect/login_success.html#access_token=...
So you have to detect the redirect and retrieve the access token from the URL.
Thanks quinten!
However, I've managed to solve my own problem by using the C# Facebook SDK.
This software development kit has been a really great help!
There are a lot of samples included (including authorisation)
Anyone who programs in .NET with facebook should check it out! Coding for facebook is now much easier.
http://facebooksdk.codeplex.com/

Categories