How to push to Bitbucket repository with access token? - c#

I used to get the access token from Bitbucket
(with the help of this documentation https://confluence.atlassian.com/display/BITBUCKET/OAuth+on+bitbucket#OAuthonbitbucket-ObtaininganOAuthConsumer)
so I want to pull/push from the logged in user's repository.
How can I use the Bitbucket REST APIs to do that with C# from an ASP.NET MVC application? I would like to implement my logic with the help of this documentation:
https://confluence.atlassian.com/display/BITBUCKET/Use+the+Bitbucket+REST+APIs
I know there is a way to list a user repo with HTTP Authentication like this:
string url = "https://bitbucket.org/api/1.0/user/repositories/";
var request = WebRequest.Create(url) as HttpWebRequest;
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("username" + ":" + "password"));
request.Headers.Add("Authorization", "Basic " + credentials);
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
}
But how can I use the token value and secret to push/pull to repository?
Thank you very much!

Looking at the Documentation you sent, https://confluence.atlassian.com/display/BITBUCKET/repositories+Endpoint+-+1.0 - you cannot push/pull to the repository with the API, instead you use the normal way to interact with the git repo - using a commandline tool or whatnot.
You may only alter the meta-data through the API: https://confluence.atlassian.com/display/BITBUCKET/repository+Resource+1.0#repositoryResource1.0-PUTarepositoryupdate
So just use the API client that is commandline: git

Related

How to send an access_token and id_token to an api using System.Net.Http

how can you send both the access_token and id_token to your api using System.Net.Http? when i was testing my api with postman it seemed to send both tokens and returned the individual user information I needed (a list of products the user is selling). I am unsure how I can do this in my Xamarin app and have being stuck on this for quite some time. I am able to send the access_token as shown below but anything I have tried when sending both tokens has returned a 404 not found. (unauthorized is corrected to a 401 so the access_token is still working)
public async Task<string> GetResponseJsonString(string url)
{
string responseJsonString = null;
var access_token = CrossSecureStorage.Current.GetValue("access_token");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
HttpResponseMessage response = httpClient.GetAsync(url).Result;
responseJsonString = await response.Content.ReadAsStringAsync();
}
return responseJsonString;
}
Note: I am aware the id_token should contain the user information and it should be decoded rather than sending requests for user information. I looked at this and have been unable to find a library that works in a xamarin PCL. I looked at JosePCL.Jwt but was unable to get it to work. I figure since any time I need user information it is returning information from my database that it made sense to send both tokens with the request and let my api get the user information.
This is entirely dependent on the API you're calling. I've never seen an API that needs something more than the access_token it's provided back to you. It's possible you have the nomenclature incorrect here.
Do you mean "access key & secret"? Or are you certain you have an access_token?
In the former case, normally API's will expect things as followed:
Append the key & secret together separated by a ":"
Base64 Encode
Set the Authorization Bearer|Basic header with the result
It's also worth asking if you've tried passing in the id_token as the Authorization header?
It's also also worth asking if you can provide us with a screen capture of the successful response from postman (make sure you obfuscate the sensitive data).
It's also also also worth pointing out an optimization tweak for your code. Since you're using async, it seems you probably are somewhat concerned about performance. Have a look at this article, discussing the disposability of HttpClient. As a better alternative, use HttpRequestMessage as follows:
public async Task<string> GetResponseJsonString(string url)
{
string responseJsonString = null;
var req = new HttpRequestMessage(HttpMethod.Get, "/your/api/url");
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
using (var resp = await client.SendAsync(req))
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
{
if (resp.IsSuccessStatusCode)
{
responseJsonString = await sr.ReadToEndAsync();
}
else
{
string errorMessage = await sr.ReadToEndAsync();
int statusCode = (int)resp.StatusCode;
//log your error
}
}
return responseJsonString;
}
Where client is a reference to a statically shared instance of HttpClient. My preferred way to do all this, is to wrap my API calls, usually one-file-per-service. I inject this service as a singleton, which will broker it's own static instance of HttpClient. This setup is even more straightforward if you're using .NET Core.

Accessing TradeKing (or any pre-authorized API) with C#/.NET

When setting up an application with TradeKing, you get:
A Consumer Key
A Consumer Secret
A Oauth Token
A Oauth Token Secret
For accessing TradeKing's API, that's apparently all you need to build personal applications. However, I can't find a way to build the correct Oauth headers in C#/.NET.
The examples seem fairly simple, like this Node.js sample. The Oauth library for Node.js takes care of generating the appropriate headers. There are similar samples for a few other languages, but they all seem to have libraries to build the proper header from the provided keys and tokens. I can't find a library to do this with C#/.NET.
I'm trying to wrap my head around what's going on in this SO question that builds the headers from scratch, but it's pretty advanced. I'm poking around in the ASP.NET Security repo, because they must be handling this somewhere. But I can't quite find what I'm looking for.
How can I generate an Oauth header from these keys with .NET?
There is an open source library on CodePlex that has some Oauth management classes set up.
I still need to go through it and take out what isn't necessary, but fortunately it doesn't depend on any other classes from the repo. Once I added it to my project, it was pretty easy to test the connection:
public async Task<IActionResult> MakeRequest()
{
string result;
var oauth = new Oauth.Manager();
// _tradeKing is a configuration object I set up to hold user secrets
oauth["consumer_key"] = _tradeKing.ConsumerKey;
oauth["consumer_secret"] = _tradeKing.ConsumerSecret;
oauth["token"] = _tradeKing.OauthToken;
oauth["token_secret"] = _tradeKing.OauthTokenSecret;
var url = "https://api.tradeking.com/v1/accounts.json";
var authzHeader = oauth.GenerateAuthzHeader(url, "GET");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = authzHeader;
var response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return Content(result);
}
There are some more instructions on how to use it from this SO post.

How to make Bitbucket API calls with access token?

I created an ASP.NET MVC application which can authorize the user at Bitbucket.
I used CSharp.Bitbucket library to get the token secret and token value.
The OAuth tutorial said that with the token I can make API calls.
I know that I can call the API using basic authorization like this way:
string url = "https://bitbucket.org/api/1.0/user/";
var request = WebRequest.Create(url) as HttpWebRequest;
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("username" + ":" + "password"));
request.Headers.Add("Authorization", "Basic " + credentials);
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
}
But how can I call the API using the access token?
Thank you very much!
First you create an "Oauth Consumer" in APPS AND FEATURES section of your bitbucket account setting. This gives you a "Key" and a "Secret".
Now using these Key and Secret you ask Bitbucket for a token. In my case I made a http request to https://bitbucket.org/site/oauth2/access_token. In your case you should use a .net equivalent. I could do it with Curl or some Ajax library like this:
curl -X POST -u "yourKeyHere:yourSecretHere" https://bitbucket.org/site/oauth2/access_token -d grant_type=client_credentials
alternatively, my http request was like this (using superagent in node) with my Content-Type set to application/x-www-form-urlencoded:
request.post("https://yourKeyHere:yourSecretHere#bitbucket.org/site/oauth2/ access_token").send('grant_type=client_credentials');`
the result is like this:
{
"access_token": "blah blah blah HXAhrfr8YeIqGTpkyFio=",
"scopes": "pipeline snippet issue pullrequest project team account",
"expires_in": 3600,
"refresh_token": "hsadgsadvkQ",
"token_type": "bearer"
}
Now that you have the token, send it in a request header:
Authorization: Bearer {access_token}
More info here bitbucket's api doc

How to create and redeem coupons in Recurly, programmatically?

++++++++++++++
Actual Scenario: I am working on a site (ASP.Net using C#) where the system will have 3 different subscription plans i.e. monthly, quarterly and yearly. All the subscription plans have their own cost and pricing. Now, if the system/admin wants to give any discounts to any subscribed user (regardless of subscription plan) on their on-going subscription based on some business logic (for example, for some user it may be $4 and for other it may be $25). How can I achieve this goal. I tried PayPal and Recurly, but stuck in-between.
++++++++++++++
I have to create a coupon and redeem the same using Recurly dynamically in C#. But, as per the code mentioned in "https://docs.recurly.com/api/v1/subscription-plans", we have to use Recurly API v2, but we don't have the code to create and redeem the coupon. So, please help me on how can I create coupons and redeem the same.
When we are using below code in mentioned URL "Recurly PUT request working but returning server error", it causes error while getting response.
uri = "https://" + subdomain + ".recurly.com/v2/subscriptions/" + uuid + "/reactivate";
try
{
string xml = "<subscription><timeframe>now</timeframe></subscription>"; //also tried with blank string.
byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
HttpWebRequest renewRequest = (HttpWebRequest)WebRequest.Create(uri);
renewRequest.Headers.Add("Authorization", "Basic " + encodeB64);
renewRequest.Method = "PUT";
renewRequest.ContentType = "text/XML";
renewRequest.ContentLength = arr.Length;
Stream datastream = renewRequest.GetRequestStream();
datastream.Write(arr, 0, arr.Length);
datastream.Close();
HttpWebResponse renewResponse = (HttpWebResponse)renewRequest.GetResponse();
}
Looking for kind response and help...
We (recurly.com) just made available a release candidate of an all new API client for C# compatible with Recurly APIv2 that we highly recommend using. The client API is stable and this release will shortly become the final release pending new show-stopping bugs.
Here's how to get started using it.
Be sure set up your configuration.
Here's how to create a coupon.
Here's how to redeem coupons.
More examples are available here.
If you have further questions please don't hesitate to ask our support team! support#recurly.com.

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