如何使用访问令牌调用Bitbucket API?

6
我创建了一个ASP.NET MVC应用程序,可以在Bitbucket上对用户进行授权。 我使用CSharp.Bitbucket library来获取令牌密钥和令牌值。 OAuth tutorial说,有了令牌,我就可以进行API调用。
我知道我可以使用基本授权这种方式来调用API:
 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();
 }

但是我如何使用访问令牌调用API呢?

非常感谢!

1个回答

7
  1. First you create an "Oauth Consumer" in APPS AND FEATURES section of your bitbucket account setting. This gives you a "Key" and a "Secret".

  2. 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
    

另外,我的http请求是这样的(在node中使用superagent),我的Content-Type设置为application/x-www-form-urlencoded

    request.post("https://yourKeyHere:yourSecretHere@bitbucket.org/site/oauth2/      access_token").send('grant_type=client_credentials');`

结果如下所示:
    {
       "access_token": "blah blah blah HXAhrfr8YeIqGTpkyFio=",
       "scopes": "pipeline snippet issue pullrequest project team account",
       "expires_in": 3600,
       "refresh_token": "hsadgsadvkQ",
       "token_type": "bearer"
    }
  1. 现在您已经拥有令牌,请将其发送到请求头中: Authorization: Bearer {access_token}

更多信息请参见Bitbucket的API文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接