-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bad Credentials, token works fine with curl
#1753
Comments
curl
Reinstalled my virtual environment, reinstalled all the packages: >>> from github import Github
>>> token = "thisismytokenfromdevelopersettingsongithub"
>>> gh = Github(token)
>>> gh.get_user("finnkauski")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/arturas/projects/gh_wrangler/.venv/lib/python3.8/site-packages/github/MainClass.py", line 271, in get_user
headers, data = self.__requester.requestJsonAndCheck(
File "/Users/arturas/projects/gh_wrangler/.venv/lib/python3.8/site-packages/github/Requester.py", line 317, in requestJsonAndCheck
return self.__check(
File "/Users/arturas/projects/gh_wrangler/.venv/lib/python3.8/site-packages/github/Requester.py", line 342, in __check
raise self.__createException(status, responseHeaders, output)
github.GithubException.BadCredentialsException: 401 {"message": "Bad credentials", "documentation_url": "https://docs.github.com/rest"}
>>> Edit |
What do you see being sent when you enable debug logging? |
Also, take a look at the scope of the token. Make sure |
Got the same problem using an Access token with everything checked.
Also script and token works on a centos7 (py3.6) machine, so it seems to be an os related issue
Curl works fine:
Pip output:
|
@maikelpoot And how are you passing the token to the Github() object? |
Tried both Also took a dive in to |
Add |
Had tried that before, makes no difference but the user-agent in the debug logging :-)
|
I'm also seeing what feels like bogus
Whereas the same query with the same token works with curl: What's weird is that, to my knowledge, it used to work until I deleted the token and created a new one. At first I thought it could be related to GitHub's new token format but when I tried another "old" token I still had, it also failed with Bad Credentials so I figure the issue might be elsewhere. |
So I wonder if this is due to redirects -- could you try with 1265747 applied (you can ignore the test) and see if that helps any? |
I came back to the project I was working on and it suddenly worked again without (to my knowledge) changing anything of significance -- I tried creating a new token and now I can reproduce the "Bad Credentials" issue again. I deleted the previous token that worked but in hindsight I shouldn't have done that to do more troubleshooting. It's a token I had just created last week. Could there be some sort of propagation period or lag before the token starts working everywhere ? I will investigate some more and find out if I can get to the bottom of the issue. Edit: btw applying 1265747 doesn't resolve the issue |
I spent some more time on this and it may turn out that the issue was caused by a caching behavior in the tool that I am running where it may cache prior tokens. I'll report back if I find out that the issue is related to pygithub but it doesn't look to be the case. Sorry for the noise ! |
Running into same issue here. Using PyGithub 1.55 The issue seems to be intermittent - so it would work one time, but won't work next run a few seconds later, then it won't work for X times, and then it might work eventually. Very unreliable = no use. |
Something is not working well here. I've been trying to use PyGithub with a new token, it has every permission it needs, works properly for the same query in curl, yet it fails with PyGithub. edit: After some debugging into the library, it seems that the |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
I am having similar issues, thanks to the comment by @scorchio I was able to figure it out: My code was trying to fetch the branch
I'm now working around this by directly fetching |
I'm having the same problem. TOKEN=`cat gh_token`
curl -v -H "Authorization: token $TOKEN" https://api.github.com/user A portion of the HTML payload returned is: {
"login": "meangrape",
"id": 9083,
"node_id": "MDQ6VXNlcjkwODM=",
"avatar_url": "https://avatars.githubusercontent.com/u/9083?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/meangrape",
"html_url": "https://github.com/meangrape",
"followers_url": "https://api.github.com/users/meangrape/followers",
"following_url":
"https://api.github.com/users/meangrape/following{/other_user}",
"gists_url": "https://api.github.com/users/meangrape/gists{/gist_id}",... With the following python the error is from github import Github
token = open("gh_token").readline().strip()
g = Github(token)
print(g.get_user().get_orgs().totalCount) with a stacktrace BadCredentialsException Traceback (most recent call last)
Input In [26], in <module>
----> 1 print(g.get_user().get_orgs().totalCount)
File ~/Library/Caches/pypoetry/virtualenvs/gh-repo-perms-6skLoHCD-py3.10/lib/python3.10/site-packages/github/PaginatedList.py:149, in PaginatedList.totalCount(self)
147 # set per_page = 1 so the totalCount is just the number of pages
148 params.update({"per_page": 1})
--> 149 headers, data = self.__requester.requestJsonAndCheck(
150 "GET", self.__firstUrl, parameters=params, headers=self.__headers
151 )
152 if "link" not in headers:
153 if data and "total_count" in data:
File ~/Library/Caches/pypoetry/virtualenvs/gh-repo-perms-6skLoHCD-py3.10/lib/python3.10/site-packages/github/Requester.py:353, in Requester.requestJsonAndCheck(self, verb, url, parameters, headers, input)
352 def requestJsonAndCheck(self, verb, url, parameters=None, headers=None, input=None):
--> 353 return self.__check(
354 *self.requestJson(
355 verb, url, parameters, headers, input, self.__customConnection(url)
356 )
357 )
File ~/Library/Caches/pypoetry/virtualenvs/gh-repo-perms-6skLoHCD-py3.10/lib/python3.10/site-packages/github/Requester.py:378, in Requester.__check(self, status, responseHeaders, output)
376 output = self.__structuredFromJson(output)
377 if status >= 400:
--> 378 raise self.__createException(status, responseHeaders, output)
379 return responseHeaders, output |
With Python3, |
I think it would be useful to set the log level to DEBUG, then the log would show what ulrllib3 is doing (including retries and redirects): import logging
logging.root.level = logging.getLevelName('DEBUG') |
I see this in the log output. I guess the important part is where the request for the master branch returns a
|
This is so hard to reproduce. Can everyone who observes this issue here please give the following details:
|
If someone who can reproduce the issue could please do the following:
elif requestHeaders["Authorization"].startswith("token"):
headersForRequest["Authorization"] = "token (oauth token removed)" with elif requestHeaders["Authorization"].startswith("token"):
import hashlib
token = requestHeaders["Authorization"][5:]
token = hashlib.md5(token.encode('utf-8')).hexdigest()
headersForRequest["Authorization"] = f"token ({token})"
import github
github.enable_console_debug_logging()
token = '...'
gh = github.Github(token)
gh.get_repo('totycro/stacs').get_branch('master') Now, instead of
you should see:
Please verify that the hashes behind |
I don't have
My output doesn't consist of 2 lines, just the normal debug log info.
|
Hay, I had the same problem just now and I just enabled all the checkboxes when creating the token, so the error stopped appearing |
I'd prefer not to give all permissions to a token that doesn't need them. Though I can try adding them one at a time and see if that helps. |
Actually, that was not the problem. Then I discovered that every time I made a commit, my token became invalid. This happened because the token was in one of the files in the repository. |
Ohh |
I am also facing this error, and am able to consistently recreate it on 1.55 when all of these happen at once:
Here is my script that consistently recreates the issue: from os import getenv
import logging
from github import Github
logging.basicConfig(
level="DEBUG",
)
access_token = getenv("GITHUB_TOKEN")
gh = Github(access_token)
github_repo = gh.get_repo("whoopnip/check-if-issue-exists-action")
print(github_repo.name) When running this script with GITHUB_TOKEN=ghp... then it fails. Without a token, it succeeds. Removing debug logging, it succeeds either way. And when switching the url to |
When it gives "message": "Bad credentials", There can be only one possible reasons: you token is not valid. Most probably, your are not setting it properly. Would suggest you to use below one command: then try it. |
Hey folks!! I figured it out; at least in my instance. It looks like it has to do with a minor change with how the python requests library handles auth headers. You can't specify the header manually as there's a special location that needs to be updated. Line 122 in 001970d
For a test I inserted this below that line:
This is based on how auth is set here for sessions: https://requests.readthedocs.io/en/latest/user/advanced/ I'm not sure why the auth header is overwritten when auth is unset BUT it's got me working right now. Going to see if I can work on a patch Edit 1: Edit 2: Which time wise matches when this issue started |
I had the same issue. The first time when I used my token everything is fine. Then it did not work anymore. Again I created a new token (all permissions checked) and the first time it worked then again not. Later I checked my emails and saw that Github send me a notification, where they automatically revoked my developer token because they found it in a git commit. (I made a test commit with my original token as an input test). Maybe some of you people did the same as me, so the token got revoked. @ShiftedMr I checked out your PR and unfortunately, it couldn't solve the above-described scenario, where Github revokes the token automatically. |
@efstratios97 My issue was not related to the revoked token. |
For me, the issue was the Solution:
|
Me, too. I'd been successfully using PyGitHub for a couple hours of programming. Then, running the same two-line script that had worked previously, I have no |
I had the same issue with github api and python requests. $ grep 'github.com' ~/.netrc -A 2
machine api.github.com
login ***
password *** Removing the entry fixes the issue. BasicAuth or a custom authenication class can be used if you have no controll over .netrc file: import requests
GITHUB_KEY = "ghp_***"
class BearerAuthToken(requests.auth.AuthBase):
def __call__(self, r):
r.headers['Authorization'] = f'Bearer {GITHUB_KEY}'
return r
requests.post(
"https://api.github.com/graphql",
json={"query": "query { viewer { login }}"}},
auth=BearerAuthToken() ,
) |
I almost spent ~2 hours trying to figure out the issue. As @injaelee said, I have removed the github related entries in .netrc file and i was able to use ghe_instance.get_user().get_repo().delete() to delete the repo. |
Happened to me when I accidentally committed the token. GitHub immediately revoked it. |
I've just had a very similar issue myself:
What helped: do not use "Fine-grained tokens" that are still in beta, use "Tokens (classic)". Now everything works like a charm. Feels like a GitHub bug. |
I have similar use case but the difference is that I use classic tokens instead of fine-grained ones. My program also worked fine for the last few days but failed when my token expired and I regenerated my token. I use So the core problem to me is the cached old objects containning expired tokens. The reproducible code is in https://github.com/Lslightly/demo-BadCredentials |
Hey folks,
Used a personal access token as authentication, yet it does not work through python. No issues when using same token with curl, however here is the issue when using it in python.
Meanwhile in curl:
I honestly have no clue what's up. I went into the source and found the
Requester
code and it looks like it generates the header correctly. But for some reason it doesn't really fly.I am using version:
1.53
The text was updated successfully, but these errors were encountered: