OAuth on Bitbucket

Bitbucket REST API integrations, and Atlassian Connect for Bitbucket add-ons, can use OAuth 2.0 or 1.0 to access resources in Bitbucket.

OAuth 2.0

Our OAuth 2 implementation supports all 4 of RFC-6749's grant flows.

This section provides the basic OAuth 2.0 information to register your consumer and set up OAuth 2.0 to make API calls.

Our OAuth 2.0 implementation is merged with our existing OAuth 1.0 in such a way that existing OAuth 1 consumers automatically become valid OAuth 2 clients.

Create a consumer

OAuth needs a key and secret, together these are know as an OAuth consumer. You can create a consumer on any existing individual or team account. To create a consumer, do the following:

  1. Log into your Bitbucket account.
  2. Click accountname > Manage account from the menu.
    The Account page appears.
  3. Click OAuth from the menu bar.
    Click the Add consumer button.  
    The system requests the following information:

    Field Description
    Name The display name for your consumer. This must be unique within your account. This is required.
    Description An optional description of what your consumer does.
    Callback URL

    Required for OAuth 2.0 consumers.

    When making requests you can include a call back URL in the request:

    • If you do include the URL in a request it must be appended to the same URL configured in the consumer. So if your consumer callback URL is example.com/add-on the URL in your request must be something similar to example.com/add-on/function.

    • If you don't include the URL in the request we redirect to the callback URL in the consumer.
    URL An optional URL where the curious can go to learn more about your cool application.
  4. Click Save
    The system generates a key and a secret for you.
  5. Toggle the consumer name to see the generated Key and Secret value for your consumer.

Optionally, you could also obtain a consumer using the oauth Resource on the users Endpoint - 1.0.

Access tokens

We support all 4 of RFC-6749's grant flows to obtain access tokens through the following URL's:

Grant types

Authorization code grant

The full-blown 3-LO flow. Request authorization from the end user by sending their browser to:

The callback includes the ?code={} query parameter that you can swap for an access token:

Implicit grant

Useful for browser-based operations without server-side back end support. This grant type requests authorization from the user by directing their browser to:

That will redirect to the callback URL with a fragment containing the access token (#access_token={token}&token_type=bearer) where your page's JavaScript can pull it out of the URL.

Making requests

Once you have an access token, as per RFC-6750, you can use it in a request in any of the following ways (listed from most to least desirable):

  1. Send it in a request header: Authorization: Bearer {access_token}
  2. Include it in a (application/x-www-form-urlencoded) POST body as access_token={access_token}
  3. Put in the query string of a non-POST: ?access_token={access_token}

Refresh tokens

Our access tokens expire in one hour. When this happens you'll get 401 responses.

Most access token grant response therefore include a refresh token that can then be used to generate a new access token, without the need for end user participation:

Scopes

Scopes are defined on the client/consumer instance. Bitbucket does not currently support the use of the optional scope parameter on the individual grant requests.

When the scope parameter is provided, Bitbucket will validate that it contains no scopes that were not already present on the client/consumer and fail if additional scopes are requested, but asking for fewer scopes will not affect the resulting access token.

Cloning a repository with an access token

Since add-ons will not be able to upload their own SSH keys to clone with, access tokens can be used as Basic HTTP Auth credentials to clone securely over HTTPS.

The literal string x-token-auth as a substitute for username is required.

Our process is similar to GitHub, yet slightly different: the difference is GitHub puts the actual token in the username field.

OAuth 1.0

Bitbucket authenticates your application and authorizes access using the OAuth 1.0a with HMAC-SHA1 (shared secret) signatures. We support both 3-Legged and 2-Legged OAuth. RSA-SHA1 (the public/private keys feature) is  not  currently supported.  

If you are building a new client, integration, or Atlassian Connect for Bitbucket add-on we strongly suggest using OAuth 2.0 as the preferred authentication method.

This section steps you through the basic OAuth 1.0a work flow of registering your consumer and getting set up to make API calls. It is difficult to test this work flow with curl. If you don't want to write a quick client, you can try it for yourself interactively using a testing site. The site will create the more complex, calculated values OAuth needs (such as timestamps) for you.

Finally, you should use an existing OAuth library for your application instead of implementing the protocol yourself. Numerous reusable libraries in many languages exist for use with OAuth – they are listed on the official oauth.net site.

Step 1. Create an OAuth key and secret

OAuth needs a key and secret together these are know as an OAuth consumer. You can create a consumer on any existing individual or team account. To create a consumer, do the following:

  1. Log into your Bitbucket account.
  2. Click accountname > Manage account from the menu.
    The Account page appears.
  3. Click OAuth from the menu bar.
    Click the Add consumer button.  
    The system requests the following information:

    Field Description
    Name The display name for your consumer. This must be unique within your account. This is required.
    Description An optional description of what your consumer does.
    Callback URL

    Required for OAuth 2.0 consumers.

    When making requests you can include a call back URL in the request:

    • If you do include the URL in a request it must be appended to the same URL configured in the consumer. So if your consumer callback URL is example.com/add-on the URL in your request must be something similar to example.com/add-on/function.

    • If you don't include the URL in the request we redirect to the callback URL in the consumer.
    URL An optional URL where the curious can go to learn more about your cool application.
  4. Click Save
    The system generates a key and a secret for you.
  5. Toggle the consumer name to see the generated Key and Secret value for your consumer.

Optionally, you could also obtain a consumer using the oauth Resource on the users Endpoint - 1.0.

Step 2. Request a request token from Bitbucket

Your application first needs to get an OAuth request token from Bitbucket. It does this through a POST request to https://bitbucket.org/api/1.0/oauth/request_token . Your POST must include:

Parameter Required Description
oauth_consumer_key Yes The consumer key. This value is generated by Bitbucket.
oauth_nonce Yes

A random string, uniquely generated for each request. The nonce allows the Service Provider to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel (such as HTTP).

oauth_signature Yes The signature as defined by the consumer. OAuth does not mandate a particular signature method, as each implementation can have its own unique requirements. Currently, Bitbucket only supports HMAC-SHA1 or PLAINTEXT signatures.
oauth_signature_method Yes The signature method the consumer used to sign the request. This is determined by your application.
oauth_timestamp Yes The number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value MUST be a positive integer and MUST be equal or greater than the timestamp used in previous requests. If the timestamp is not within a few minutes either side of the actual current time, the request may be rejected.
oauth_callback Yes

The URL to redirect a user to should they approve your application's access to their account. For example:

http%3A%2F%coolapp.local%2Fauth.php,bitbucketclient%3A%2F%2Fcallback

The following is an example of a POST call:

https://bitbucket.org/api/1.0/oauth/request_token?oauth_version=1.0&oauth_nonce=7f2325b3c36bd49afa0a33044d7c6930&oauth_timestamp=1366243208&oauth_consumer_key=HUpRcDUduZrepL6sYJ&oauth_callback=http%3A%2F%2Flocal%3Fdump&oauth_signature_method=HMAC-SHA1&oauth_signature=qZyTwVA48RzmtCHvN9mYWmlmSVU%3D

Bitbucket validates your request and responds with a set of temporary credentials:

HTTP/1.1 200 OK
Server: nginx/1.2.4
Date: Thu, 18 Apr 2013 15:56:00 GMT
Content-Type: application/x-www-form-urlencoded
Content-Length: 112
Connection: keep-alive
X-Served-By: bitbucket05
Content-Language: en
X-Static-Version: 209da49a2dfa
Vary: Accept-Language, Cookie
X-Version: 913e0af5d84d
ETag: "cd2fb61a6e2ac48da4b1c3b377aca5d7"
X-Request-Count: 260
Strict-Transport-Security: max-age=2592000
X-Content-Type-Options: nosniff
oauth_token_secret=3PddbU47vqStvrFag8Dwnpqs28HxAKeq&oauth_token=4vyW6b49ZxcZDK64eY&oauth_callback_confirmed=true

These credentials are the following:

Value Description
oauth_token_secret

The token shared-secret.

oauth_token

The request token.

oauth_callback_confirmed
Must be present and true.

Step 3. Redirect the user to Bitbucket to authorize your application

Access tokens allow your application to interact with Bitbucket on behalf of user. Before your application can get access tokens, the Bitbucket user must authorize your application to act on his/her behalf. To get authorization, your webserver makes a GET to https://bitbucket.org/api/1.0/oauth/authenticate and passes the oauth_token (request token) returned in the last step's POST. For example, the following call:

https://bitbucket.org/api/1.0/oauth/authenticate?oauth_token=4vyW6b49ZxcZDK64eY

If the user isn't logged into Bitbucket, Bitbucket asks the user to login. In this way, your application verifies the identity of the account holder. Then, Bitbucket confirms with the user that your application should have account access:


Bitbucket then redirects the user to the callback provided in the previous Step 2 above. Bitbucket returns in the redirect an oauth_verifier along with the oauth_token your application provided in its request.

http://localhost/?dump&oauth_verifier=2287965216&oauth_token=URjPjc8CxLgNBdh7zL

Your application should store the oauth_verifier so you can use it in the next step. Bitbucket requires use of the oauth_verifier which is an OAuth 1.0a feature.

Step 4. Request an Access Token

The last step is to obtain credentials that let you access resources on Bitbucket. Your application gets these by making a POST call to https://bitbucket.org/api/1.0/oauth/access_token . Your application must construct a request URI by adding the following parameters:

Parameter Required Description
oauth_consumer_key Yes The consumer key. This value is generated by Bitbucket.
oauth_token Yes The oauth_token returned by the request_token call.
oauth_nonce Yes

A random string, uniquely generated for each request. The nonce allows the Service Provider to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel (such as HTTP).

oauth_signature Yes The signature as defined by the consumer. OAuth does not mandate a particular signature method, as each implementation can have its own unique requirements. Currently, Bitbucket only supports HMAC-SHA1 signatures.
oauth_signature_method Yes The signature method the consumer used to sign the request. HMAC-SHA1 is the method supported by Bitbucket.
oauth_timestamp Yes The number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value MUST be a positive integer and MUST be equal or greater than the timestamp used in previous requests. If the timestamp is not within a five minutes either side of the actual current time, the request may be rejected.
oauth_verifier Yes

This value is returned as a query parameter in the URL that the token authorization page redirects to after the user clicked "grant permission" on Bitbucket. For example:

http://localhost?oauth_verifier=0352671347&oauth_token=QAx6g4npas3tdARQUY

An example of this request is:

https://bitbucket.org/api/1.0/oauth/access_token?oauth_version=1.0&oauth_nonce=d6d773f282740f2b25112f819b0d3b7c&oauth_timestamp=1366242978&oauth_consumer_key=HUpRcDUduZrepL6sYJ&oauth_verifier=2287965216&oauth_token=YRpuxpCLYCJpXJyUE2&oauth_signature_method=HMAC-SHA1&oauth_signature=vmJ3LuudxaW5Rs7xLJa56TLZwPE%3D

The request returns an access token such as the following:

oauth_token_secret=aH9bzCKjKT5uXWueeENr9LKNh2jyyUVj&oauth_token=NqFQPmgsa4QQ9StW2R

With this access token your application can make Bitbucket API calls.

Was this helpful?

Thanks for your feedback!

45 Archived comments

  1. User avatar

    Anonymous

    Just to say, i did use Zend Library to work with oauth and it is the best way to get the job done. Tried many libraries but the best use it was Zend OAuth. 

    30 May 2012
  2. User avatar

    Anonymous

    AIn't this cool? Bitbucket is awsome

    20 Jan 2013
  3. User avatar

    Daniel Knell

    can I use the oauth credentials to download a tarball of a repository?

    22 Feb 2013
    1. User avatar

      Anonymous

      Oh, really...

      I hope you will enhance this oauth access in the future.

      09 Sep 2013
  4. User avatar

    Kamran Mackey

    Does your API work with Zapier?

    11 Apr 2013
    1. User avatar

      manthony

      Kamran,

      I've used Zapier but not with the BB APIs.  There is no reason they shouldn't work.  You should give it a try – it is a good idea. Let me know how it goes...

      Mary

      12 Apr 2013
  5. User avatar

    Anonymous

    My god some actual Sample Code would be nice for these API docs. In various languages!

    03 May 2013
    1. User avatar

      manthony

      We have this page: OAuth Consumer Examples with a single sample but we have plans to add more.  Let me know if that doesn't work for you.

      06 May 2013
  6. User avatar

    Gabriel Petrovay

    Are there any plans to add OAuth2 ?

    I've created an issue for this: https://bitbucket.org/site/master/issue/7280/are-there-any-plans-to-adding-switching-to

    06 May 2013
    1. User avatar

      manthony

      No that I know of; filing a ticket was the right way to go.

      10 May 2013
      1. User avatar

        Gabriel Petrovay

        Erik van Zijst said inside the issue above to open an issue "so others can find it and vote for it." What did he mean?

        10 May 2013
        1. User avatar

          manthony

          When you create an issue, other people can watch it.  A user watching an issue is our equivalent to voting something up.  Users can search our issues database and find issues related to their questions/suggestions.

          10 May 2013
  7. User avatar

    Gabriel Petrovay

    Typo:

    Step 2. Request an request token from Bitbucket

    (2 times: both on the summary and in the text)

    09 May 2013
    1. User avatar

      manthony

      Fixed.  Thanks for the catch.

      10 May 2013
  8. User avatar

    Gabriel Petrovay

    Can you please provide an example the the end of this article showing how to use the obtained access token.

    Right after you say: "With this access token your application can make Bitbucket API calls.". Or maybe give us a link to an example (oauth.org, etc.)

    The "OAuth Consumer Examples" is not low-level enough. The oauth.net is all about Oauth version 2 (that's why the question above). I don't know what to do with:

    oauth_token_secret=aH9bzCKjKT5uXWueeENr9LKNh2jyyUVj&oauth_token=NqFQPmgsa4QQ9StW2R

    Do they go in the request URL's or are they request headers?
    Does casing matter if headers?
    Are there any other steps required other then attaching them as query parameters/headers?

    Thanks for help!

    09 May 2013
  9. User avatar

    manthony

    Gabriel, 

    At the moment, our only example is OAuth Consumer Examples.  What you want is a more detailed client and you might be able to find one in the existing repositories.  Just search here for bitbucket:

    https://bitbucket.org/repo/all/

    We'll add a more detailed tutorial when time allows.

    Mary

    10 May 2013
  10. User avatar

    Anonymous

    Hi,

    I am able to validate user and call the API when the user authorizes from bitbucket page. What values should I save for future API call by the application on a regular interval (or based on git hook)? I see the authorization is saved on bitbucket page- not sure how to use that. I tried to use rtoken, rsecret and oauth_verifier from the first request but did not work (Provider returned: Invalid OAuth verifier.).

     

    Thanks,
    Maruf

    26 May 2013
    1. User avatar

      manthony

      Maruf,

      Did you look at our OAuth Consumer Examples page?  Depending on your experience, you may find an OAuth manual such as Getting Started with OAuthh 2.0 helpful.

      Mary

      28 May 2013
  11. User avatar

    Anonymous

    Hi,

    I have a strange problem. I am able to get an access token. I construct a URL as below and replace %s with appropriate values.

    https://bitbucket.org/api/1.0/repositories/nasir/rasul/branches?oauth_token_secret=%s&oauth_token=%s

    When I invoke an http request .get, I get Forbidden response. 

    If I paste the same URL in the browser I get correct response. I am absolutely stumped. Is there any other parameter bitbucket expects?

    Thanks.

    Nasir

    23 Jun 2013
    1. User avatar

      Anonymous

      solved it - using Scribe, one of the oauth libraries. My problem was probably the signing the request before accessing the resource.

      23 Jun 2013
  12. User avatar

    Ville Saalo

    In Step 3, "Redirect the user to Bitbucket to authorize your application", is it possible to get a mobile-optimized login page? It makes for a really bad user experience when the large desktop layout is crammed into a small smartphone screen. The user must zoom in and scroll around just to be able to log in. (sad)

    Edit: I've created an issue about this: https://bitbucket.org/site/master/issue/7744/oauth-login-page-to-support-mobile

    11 Jul 2013
  13. User avatar

    Anonymous

    hi,

    I'm looking for advice really - i want to grab meta data from my private repository to show on my main website meta such as bug tracking info and issues-tracking info. oAuth sounds like what i want but having never used it i don't know. Is oAuth the way to go or can i make calls form my php scripts without it. I would like to use xml or json format etc. My Site visitors will not use the end-point - it will only be my scripts on my website making calls to my bitbucket repository

     

    thanks in advance

    07 Aug 2013
    1. User avatar

      manthony

      You know, there are lots of ways you can go about this.  You could, for example, use scripts to construct that data locally and push it out a website.  If you used scripts you could use a deploy key to pull the data.  You could use a build tool or a crontab type job to run these.  Any such solution would not require OAuth.  OAuth is more if you want to write software to access other user's data.

      07 Aug 2013
      1. User avatar

        anilee

        hi, (just created an account),

        Ok, so use a script on my local machine and access the raw data from the .git directory in my local project directory?  and push to my site so im bypassing bitbucket really?

        I really like the history info and tracking info shown in GIT GUI's,  sourcetree and SmartGit.

        07 Aug 2013
        1. User avatar

          manthony

          Essentially, if you are accessing your own account data you don't really need OAuth. You can use another means to authenticate to Bitbucket. If that data is something you can get from your local repository fine. If it is something you want via REST, you can use Basic Auth as you know your username / password.

          07 Aug 2013
          1. User avatar

            anilee

            yes, just read one of your previous activities 'Use the Bitbucket REST APIs' - its exactly what i was looking for - wish i'd seen this first.

            Thanks

             

             

            07 Aug 2013
  14. User avatar

    z38

    Hi,

    is there any special reason for using an exclamation point in some of the URLs (e.g. /!api/)?

    Thanks!

    11 Aug 2013
    1. User avatar

      manthony

      That is just another way to reach the same API. I need to clean that up.  Which page did you see it on?

      12 Aug 2013
      1. User avatar

        z38

        I think it occurs 4 times (once in step 2 and 4 and two times in step 3). Thank you for clarifying it!

        12 Aug 2013
        1. User avatar

          manthony

          Took care of it. Thanks for the catch.

          13 Aug 2013
  15. User avatar

    Allan Chau

    There seems to be a lack of iOS libraries supporting ARC so I decided to implement the OAuth protocol myself. Although I couldn't find it specified anywhere, when using the recommended HTML headers and HMAC-SHA1 you will need to double encode the callback URL AND include the Host header.

    27 Nov 2013
  16. User avatar

    Anonymous

    every time when i want send a request to https://bitbucket.org/api/1.0/oauth/access_token

    i get Could not verify OAuth request.

     whats going on here? -.-

    31 Jan 2014
    1. User avatar

      Marcus Bertrand [Atlassian]

      If you're having issues, please come to support and include all headers with this request so we can help you. Also, try checking out the examples on this page.

      31 Jan 2014
  17. User avatar

    Alexander Serdcev

    Hello!

    Once the user has connected application, how can I find out his username, so I could semi list of its repository?

    Here:
    https://confluence.atlassian.com/display/BITBUCKET/users+Endpoint#usersEndpoint-GETtheuser'srepositories

    said that I should already know the username of the user. How can I get it after the user connects the application?

    15 Feb 2014
    1. User avatar

      Allan Chau

      I have the same problem, you should be using the following:

      GET https://bitbucket.org/api/1.0/user

      However, it didn't work for me.

      15 Feb 2014
  18. User avatar

    Keith Rosenberg

    Is there any way to get a personal access token (OAuth) like you can on Github? https://github.com/settings/applications#personal-access-tokens

    I am trying to setup Bitbucket with .netrc without having to actually store my password in text. See https://github.com/component/guide/blob/master/component/getting-started.md#configuring-bitbucket-access

    01 Jul 2014
  19. User avatar

    dietervds

    I struggled for a while on exactly how I had to do a request to the Bitbucket API once I had the access token.

    If you're using PHP, this is what worked perfectly for me: Install Guzzle (v4 at time of writing) with composer, and install the Guzzle OAuth Subscriber plugin. Fill in what you need, and you're good to go. You can find the plugin and usage example here: https://github.com/guzzle/oauth-subscriber

    14 Aug 2014
  20. User avatar

    Kaz Nishimura

    Is there any way to force re-authentication of any already logged-in user in OAuth sign-in? It seems some cookies identifying the user are remembered and I cannot make users switch their accounts even if I throw away the old access token.

    If you cal tell which cookie is identifying a user, I can try to delete it on the client side.

    27 Nov 2014
  21. User avatar

    Kevin Chugh

    When to access tokens expire?  Is there a way to request a permanent or 30 day token? I am seeing them not last overnight, so I'm guessing the expiration is less than 8 hours which isn't terribly useful.  

    11 Mar 2015
  22. User avatar

    Yves Dufour

    Basic Authentication on Team account

    I created a Team account with admin and dev groups...

    I want my dev to be able to run ruby scripts (from their toolbox) , I guess Basic Authentication is mandatory in this case ( as their is no way to authorize scripts... as apps... no return callbacks..)  

    I added members in the dev group...  which are not Bitbucket Account owners, can they authenticate with their username + API key as a password ?

     

     

    24 Apr 2015
    1. User avatar

      Kaz Nishimura

      For non-web apps, you should be able to use a magic-cookie URL as a callback and check if a response is a redirect to the URL. You don't need to open the callback URL actually but just catch the redirect response for a verification code.

      24 Apr 2015
      1. User avatar

        Максим Ильин

        Kaz Nishimura could you please described more in detail how receive response on redirect URL for non-web apps.

        01 May 2015
        1. User avatar

          Kaz Nishimura

          If you use an in-app browser, many browsers have a measure to hook before page transitions. For example, .NET WebBrowser has the Navigating event, Android WebViewClient has method shouldOverrideUrlLoading, and so on. By using something like them, you can intercept redirects to your callback URL.

          If you are using an external browser, it can be more complicated, though. But even if you cannot intercept redirects, you can use oob (manual) verification anyway.

           

          01 May 2015
  23. User avatar

    Jesper Christensen

    I am writing a client using your OAuth 2.0 flow. 

    When getting the access_token via the "Implicit grant" flow all is fine, but a refresh_token is not returned along with the access_token?

    Shouldn't that happen or do I need to use the "Authorization code grant" flow instead?

    30 Jun 2015
  24. User avatar

    Kaz Nishimura

    I tried the new OAuth 2.0 in my Bitbucket API Client Library for Java in production using the Google OAuth Client Library as a helper. It seemed to work though I have not make any API requests yet.

    I was struggling in the token request phase since it required the Basic authentication instead of just passing client_id and client_secret as request parameters.

     

     

    18 Jul 2015
Powered by Confluence and Scroll Viewport