How to make Bitbucket API calls with access token? - c#

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

Related

How to call rest api with an oauth 2.0 authentication token in C#

In POSTMAN Go to Authorization tab
Select OAuth 2.0 from the Type dropdown
Select Request Headers from Add authorization data to dropdown
Fill the following information in Configure New Token section:
Token Name: ‘My OAuth2 token’ (You can name it as your wish)
Grant Type: Client Credentials
Access Token URL: https://service.endpoint.com/api/oauth2/token
Client ID: The Client_Id generated earlier (ABCD)
Client Secret: The Client_Secret generated earlier(1234f)
Click on Get New Access Token button
I then need to make a get call using a bearer token.
I can get this to work in Postman, but have hit a wall trying to work out how to implement it in C#.
I need C# code for calling a REST API with an access token.
Here is a sample C# request to make and Oauth call with authorization token.
Install the restSharp nuget package.
//#Install RestSharp nuget package
//using RestSharp
public async Task<RestResponse> getData(string authtoken)
{
var options = new RestClientOptions("http://sampleUrl")
{
MaxTimeout = -1,
};
var client = new RestClient(options);
var request = new RestRequest("/samplemethods/123", Method.Get);
request.AddHeader("Authorization", "Bearer " + authtoken);
RestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.StatusCode);
return response;
}

Receiving 401 "Unauthorized" error while using Google Cloud AutoML via HttpClient

I am writing a WPF application with C# that attempts to make an Google Cloud AutoML API call with HttpClient. I am able to make contact with the server but always get back an "Unauthorized" response. I have scoured StackOverflow and the AutoML documentation for any hint as to how to properly turn the "CURL" request into a simple HTTP request that I can execute programmatically within my C# application, but haven't found anything that gave enough guidance up to this point (hence my question).
Here is the CURL request that I am modeling my HTTP request after:
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/MyProjectId:predict -d #request.json
There are elements of this request that I cannot figure out how to translate into C#, namely the Authorization: Bearer component. Do I need to somehow find a token and add it to a header or something? If so, how do I acquire this token in string form? That seems to be what I'm really stuck on.
And here is the C# code that I actually have up to this point.
public async Task<object> GetPrediction(string imagePath)
{
string apiKey = "MyApiKey";
string projectId = "MyProjectId";
HttpResponseMessage response;
byte[] img = File.ReadAllBytes(imagePath);
string jsonBody = "{\"payload\":{\"image\":{\"imageBytes\":\"" + Encoding.UTF8.GetString(imgBody) + "\"}}}";
string uri = $"https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/{projectId}:predict?key={apiKey}";
string token = “MyToken”;
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
request.Headers.Authorization = new AuthenticarionHeaderValue(“Bearer”, token);
request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
response = await client.SendAsync(request);
return Task.FromResult(response);
}
This code basically makes contact, then I get back a 401 "unauthorized" status code. Any suggestions or guidance would be greatly appreciated, and if additional information is required, I would be glad to post more. Thanks!
Update:
I modified the code block to include the suggested change from Nkosi, but I am still seeing the same 401 status code.
I am not seeing the Authorization header added to request
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
like in the cURL example
set the Authorization on the request before sending it
//...
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "{token-here}");
//...

This request requires a matching csrf cookie and header. 353 code error on twitter

My script can't follow on twitter anymore. It gives this error:
This request requires a matching csrf cookie and header.
I added this header:
request.Headers.Add("x-csrf-token", token);
And this to edit token in the cookie:
cookieContainer.Add(new Cookie("ct0", token) { Domain = request.RequestUri.Host });
But it still doesn't work anymore. What should I do exactly?
I am using python to do exact the same thing and I noticed that there are some other headers you should add:
Bearer = 'Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw'
session.headers['Authorization'] = Bearer
session.headers['x-twitter-auth-type'] = 'OAuth2Session'
session.headers['X-Twitter-Active-User'] = 'yes'
session.headers['Origin'] = 'https://twitter.com'
I found that Bearer string from this file which loaded in html request:
https://abs.twimg.com/k/en/init.en.37d4e85afd8ede9741dd.js
Hope this helps.

How to push to Bitbucket repository with access token?

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

How do I do set the Authorization header of a GoogleLogin request using the new WCF REST HttpClient API

I'm using the new HttpClient class, part of the WCF REST Starter Kit, to authenticate to Google's Map Data service. I've got my ClientLogin authentication token, but I'm not sure how to take this instruction:
GET http://maps.google.com/maps/feeds/maps/userID/full
Authorization: GoogleLogin
auth="authorization_token"
and make it work in this code:
var auth = [myAuthToken]
var http = new HttpClient("http://maps.google.com/maps/feeds/maps/[myUserName]/full");
http.DefaultHeaders.Authorization = Microsoft.Http.Headers.Credential.CreateBasic("GoogleLogin", "auth=" + auth);
var response = http.Get();
The docs say: "the GET request requires an Authorization HTTP header, passing an AuthSub or GoogleLogin token." I have the token, I just don't know how to create that Authorization HTTP header correctly through that api. Anyone help?
Instead of using the CreateBasic static method, you can just pass the complete authorization header to the constructor of the Credential class. e.g.
client.DefaultHeaders.Authorization = new Credential("GoogleLogin auth=" + auth);

Categories