ilo*_*ilo 5 python jwt github3.py pygithub
我想在python中创建一个github应用程序,我被困在身份验证部分。由于默认情况下它们不支持python,因此我必须使用第三方库。生成 JWT 令牌后,我可以成功使用 curl 进行身份验证,但不能使用库进行身份验证。
我试过使用 PyGithub 和 Github.py 并且都返回了“错误的凭据”错误,所以我一定忽略了一些东西。
import jwt
from github import Github
from dotenv import load_dotenv
load_dotenv()
GITHUB_PRIVATE_KEY = os.getenv('GITHUB_PRIVATE_KEY')
GITHUB_APP_IDENTIFIER = os.getenv('GITHUB_APP_IDENTIFIER')
GITHUB_WEBHOOK_SECRET = os.getenv('GITHUB_WEBHOOK_SECRET')
message = {'iat': int(time.time()),
'exp': int(time.time()) + (10 * 60),
'iss': GITHUB_APP_IDENTIFIER}
token = jwt.encode(message, GITHUB_PRIVATE_KEY.strip().encode(), 'RS256')
gh = Github(jwt=token.decode())
for repo in gh.get_user().get_repos():
print(repo.name)
Run Code Online (Sandbox Code Playgroud)
此 curl 命令返回我的应用程序的详细信息:
curl -i -H "Authorization: Bearer YOUR_JWT" -H "Accept: application/vnd.github.machine-man-preview+json" https://api.github.com/app
Run Code Online (Sandbox Code Playgroud)
我希望代码能够验证并打印我的回购,但是我得到
Traceback (most recent call last):
File "C:/python/jeev/testing.py", line 21, in <module>
for repo in gh.get_user().get_repos():
File "C:/python/jeev\venv\lib\site-packages\github\PaginatedList.py", line 62, in __iter__
newElements = self._grow()
File "C:/python/jeev\venv\lib\site-packages\github\PaginatedList.py", line 74, in _grow
newElements = self._fetchNextPage()
File "C:/python/jeev\venv\lib\site-packages\github\PaginatedList.py", line 199, in _fetchNextPage
headers=self.__headers
File "C:/python/jeev\venv\lib\site-packages\github\Requester.py", line 276, in requestJsonAndCheck
return self.__check(*self.requestJson(verb, url, parameters, headers, input, self.__customConnection(url)))
File "C:/python/jeev\venv\lib\site-packages\github\Requester.py", line 287, in __check
raise self.__createException(status, responseHeaders, output)
github.GithubException.BadCredentialsException: 401 {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}
Run Code Online (Sandbox Code Playgroud)
Github3.py 版本:
curl -i -H "Authorization: Bearer YOUR_JWT" -H "Accept: application/vnd.github.machine-man-preview+json" https://api.github.com/app
Run Code Online (Sandbox Code Playgroud)
引发了相同的 401 错误凭据异常。我在 login_as_app 函数中包含了一个打印,所以现在它输出 JWT 令牌,我将它与 curl 命令一起使用,我得到了我想要的。奇怪的。
使用 PyGithub,你错误地使用了 API
这样就可以了
from github import Github, GithubIntegration
with open("apps-private-key.pem", "r") as secret:
private_key = secret.read()
GITHUB_APP_ID = "1234"
integration = GithubIntegration(
GITHUB_APP_ID, private_key, base_url="https://github.com/api/v3")
install = integration.get_installation("owner", "repository")
access = integration.get_access_token(install.id)
# And here it is :)
print(access.token)
gh = Github(login_or_token=access.token,
base_url="https://github.com/api/v3")
# your operations
Run Code Online (Sandbox Code Playgroud)
我花了一段时间才弄清楚这个序列,PyGithub 的文档缺少一些位。
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |