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

时间:2014-07-28 15:54:56

标签: c# oauth bitbucket restsharp bitbucket-api

我创建了一个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 个答案:

答案 0 :(得分:4)

  1. 首先,在bitbucket帐户设置的访问管理部分创建“Oauth”。这会给你一个“钥匙”和一个“秘密”。

  2. 现在使用这些Key和Secret,你会问Bitbucket一个令牌。在我的情况下,我向https://bitbucket.org/site/oauth2/access_token发出了http请求。在您的情况下,您应该使用.net等效。我可以用Curl或像这样的Ajax库来做到这一点:

    curl -X POST -u "yourKeyHere:yourSecretHere"  https://bitbucket.org/site/oauth2/access_token -d  grant_type=client_credentials
    

    或者,我的http请求是这样的(在节点中使用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"
    }
    
  3. 现在您已拥有令牌,请将其发送到请求标头中: Authorization: Bearer {access_token}

  4. 此处有更多信息bitbucket's api doc

相关问题