Can I access my private bitbucket repository with ajax and jquery?

与世无争的帅哥 提交于 2019-12-24 02:09:59

问题


On my site, I'm currently generating a list of tags from one of my repositories hosted on bitbucket.org using jquery. But in order to do this, I had make the repository public. I would prefer to keep it private.

Is it possible for to me to allow the site access to my respository in this way, while still keeping the repository private.

The code looks like this (in this form, it will produce a list in the console of the all tags).

$.ajax({
        url:"https://api.bitbucket.org/1.0/repositories/jeffreycwitt/publicrepository/tags",
        dataType: "jsonp",
        crossDomain: true,
        success: function (returndata){
           $.each(returndata, function(key, value){
               console.log(key)
    });
});

回答1:


Basically I've learned that an "Authorization header is needed." And the consensus seems to be that this cannot be done with JSONP requests in jquery. I don't really know why.

But I have been able to achieve the desired result by writing a php script that passess the authorization header through a php file_get_contents call. Then as suggested by the comments above, I can use the ajax script to load the desire data. The php script looks like this:

context = stream_context_create(array(
'http' => array(
    'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
));

// Make the request 
$json = file_get_contents($url, false, $context);

//parse data
//turn json data into an array
$obj_a = json_decode($json, true);

//get all keys of array
$tags = array_keys($obj_a);

So if anyone wants to retrieve all the tags from a private bitbucket repository, this is how you do it. Bitbucket api documentation doesn't saying anything about how to authentic into a private repository except by means of CURL. But adding the header is what you need to do if you are not using CURL.

Hope that helps someone. (Please feel free to edit this answer if you can think you explain this better).




回答2:


You can also use an app password to authenticate, to avoid exposing your account password:

const username = 'your-username'; // USERNAME, not email
const appPassword = 'app-pass';
const repoOwner = 'you-or-your-team';
const repository = 'repository-name';

$.ajax({
    url: `https://api.bitbucket.org/1.0/repositories/${repoOwner}/${repository}/tags`,
    headers: {
        Authorization: 'Basic ' + btoa(`${username}:${appPassword}`)
    },
    success: console.log,
    error: d => console.log(d.responseText),
});


来源:https://stackoverflow.com/questions/13557490/can-i-access-my-private-bitbucket-repository-with-ajax-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!