开发者

Reading the BitBucket API with Authentication for a Private Repository in C#.net

开发者 https://www.devze.com 2023-03-20 03:43 出处:网络
I\'ve been trying for a few days to get the BitBucket API to work for me, but have come to a grinding halt when it comes to getting it to work for a private repository with authentication (with the is

I've been trying for a few days to get the BitBucket API to work for me, but have come to a grinding halt when it comes to getting it to work for a private repository with authentication (with the issues set as private, when they're set to public and no authentication is needed it all works fine)

Code sample is as follows:

static void Main(string[] args)
    {
        WebProxy prox = new WebProxy("ProxyGoesHere");
        prox.Credentials = CredentialCache.DefaultNetworkCredentials;

        var address = "repositories/UserFoo/SlugBar/issues/1";
        var repCred = new CredentialCache();

        repCred.Add(new Uri("https://api.bitbucket.org/"), "Basic", new NetworkCredential("UserFoo", "PassBar"));


        WebClient client = new WebClient();
        client.Credentials = repCred;

        client.Proxy = prox;
        client.BaseAddress = "https://api.bitbucket.org/1.0/";
        client.UseDefaultCredentials = false;

        client.QueryString.Add("format", "xm开发者_如何学JAVAl");

        Console.WriteLine(client.DownloadString(address));
        Console.ReadLine();

    }

Many thanks.


I had the same problem recently, and I found two different solutions.

First, vanilla .net with HttpWebRequest and HttpWebResponse:
(this came from an answer here at Stack Overflow, but unfortunately I can't find the link anymore)

string url = "https://api.bitbucket.org/1.0/repositories/your_username/your_repo/issues/1";
var request = WebRequest.Create(url) as HttpWebRequest;

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("your_username" + ":" + "your_password"));
request.Headers.Add("Authorization", "Basic " + credentials);

using (var response = request.GetResponse() as HttpWebResponse)
{
    var reader = new StreamReader(response.GetResponseStream());
    string json = reader.ReadToEnd();
}  

Or, if you want to do the same with less code, you can use RestSharp:

var client = new RestClient("https://api.bitbucket.org/1.0/");
client.Authenticator =
    new HttpBasicAuthenticator("your_username", "your_password");
var request = new RestRequest("repositories/your_username/your_repo/issues/1");
RestResponse response = client.Execute(request);
string json = response.Content;   

By the way, I decided to use the HttpWebRequest solution for my own application.
I'm writing a small tool to clone all my Bitbucket repositories (including the private ones) to my local machine. So I just make one single call to the Bitbucket API to get the list of repositories.
And I didn't want to include another library in my project just to save a few lines of code for this one single call.


Additionally, you could use Bitbucket.Cloud.Net:

  1. get a token, for example with using Flurl.Http:
    var uvalue = "your_username OR consumer_key";// see https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html
    var pvalue = "your_password OR consumer_secret";// see https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html
    var urlAccessToken = "https://bitbucket.org/site/oauth2/" + "access_token";
    var response = await urlAccessToken
                                       .WithBasicAuth(uvalue, pvalue)
                                       .PostUrlEncodedAsync(new
                                       {
                                           grant_type = "client_credentials"
                                       })
                                       .ReceiveJson().ConfigureAwait(false);
    var token = response.access_token;

    // Do something with your authenticated client.

then, using retrieved token,

var oauth = new Bitbucket.Cloud.Net.Common.Authentication.OAuthAuthentication(token);
var bitbucket = new Bitbucket.Cloud.Net.BitbucketCloudClient("https://api.bitbucket.org/", oauth);
//your workspace name is UserFoo
//returns list of Bitbucket.Cloud.Net.Models.v2.Repository
var list = await bitbucket.GetWorkspaceRepositoriesAsync("<your workspace name>").ConfigureAwait(false);


Using WebClient is still possible, you just have to manually create the Authorization header like in the Christian Specht's answer:

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("your_username" + ":" + "your_password"));
client.Headers[ HttpRequestHeader.Authorization ] = "Basic " + credentials);
0

精彩评论

暂无评论...
验证码 换一张
取 消