我想做的是从一个小应用程序中获取私有(private) repo 数据(问题数量)。
因为我不想暴露我的 personal github access_token在请求中我搜索了另一个我认为是 OAuth 的解决方案。
所以我在 these 之后设置了一个 OAuth和 these步骤。
并在Auth0中设置权限在社交 github 设置中设置为 repo
(授予对 repos 的读/写访问权限)。
到目前为止一切正常,我可以使用我的 github 帐户进行身份验证。
但现在我不知道我必须使用哪个token
来请求
到github API
。
这是我到目前为止的相关代码:
const handleAuthentication = () => {
webAuth.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
setSession(authResult);
//here the call to the relevant function
getIssues('my-element', /*here i should pass the correct token*/); //tryed all tokens i found in authResult
} else if (err) {
alert(
`Error: ${err.error} . Check the console for further details.`
);
}
});
}
const getIssues = (element, token) => {
const request = new XMLHttpRequest();
request.open('GET', `https://api.github.com/repos/my_organization/element-${element}/issues?access_token=${token}`, true);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
const data = JSON.parse(request.responseText);
//use the data
} else {
console.log('error');
}
};
request.onerror = function(e) {
console.log('connection error: ', e)
};
request.send();
}
但这会导致 401(未授权)响应。
我没有经常使用 XMLHttpRequests
,我敢肯定,我在这里遗漏了一些基本的东西。
现在我什至不确定 oAuth 是否是实现我想要的目标的正确方法。
如有任何帮助,我们将不胜感激。
编辑:
与此同时,我做了更多研究并发现(here),缺少一些步骤来获取正确的用户 access_token 以连接到 github api。
我会尝试完成这些步骤,如果可行,我会发布答案。
如果有人知道如何准确地做到这一点,仍然会很感激一个明确的答案。
最佳答案
要获取 repo 的问题列表,请调用此 API 端点:
https://api.github.com/repos/${owner}/${repository}/issues
${owner}
是组织名称(不是 你的 github 用户名),${repo}
是 repo你想列出问题。
作为引用,文档位于此处:https://developer.github.com/v3/issues/#list-issues-for-a-repository .然而,与许多 OAuth 端点文档一样,这是神秘的,因此需要数小时的修补。
有一个实时工作的代码片段,因此您可以查看示例代码、对其进行测试和调整:https://jsfiddle.net/son74dj2/
代码片段解释如下。
它使用 https://oauth.io服务及其 SDK(下面代码中的 OAuth 类),这不是必需的。然而,OAuth.io 使您能够仅使用前端(例如 Javascript)来实现 OAuth 流程,因此实时工作代码片段可以自包含在一个 jsfiddle 中,可以轻松共享、调整、测试甚至只是剪切和-贴在你的网站上。
$('#github-button').on('click', function() {
// Initialize with your OAuth.io app public key
OAuth.initialize('YOUR OAUTH.IO PUBLIC KEY');
// Use popup for oauth
OAuth.popup('github').then(provider => {
const repository = 'YOUR REPOSITORY';
const owner = 'REPOSITORY OWNER';
provider.get(`/repos/${owner}/${repository}/issues`).then(data => {
alert('Now you could see list of issues in the console!')
console.log('Issue list:', data);
})
});
})
希望这有助于您理解和测试端点,而无需花费数小时来弄清楚文档以及修改 url 和参数。
注意:您需要有权访问存储库,存储库所有者需要授予您该权限。截图详情见原文:https://tome.oauth.io/providers/github/get-repository-issue-list
关于javascript - 使用 OAuth 和 Auth0 进行身份验证后获取 Github 存储库数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692773/