How to supply Personal Access Token via the session_auth to the Client and proxy config #153
-
Maybe a stupid question, but I'm struggling trying to supply a Personal Access Token from myapp to a private github repository. Everytime app check_for_updates, it returns a 404 log error.
I tried: from requests.auth import AuthBase
class HTTPBearerToken(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['authorization'] = f'Bearer {self.token}'
return r
client = Client(
app_name=settings.APP_NAME,
app_install_dir=settings.INSTALL_DIR,
current_version=settings.APP_VERSION,
metadata_dir=settings.METADATA_DIR,
metadata_base_url=settings.METADATA_BASE_URL,
target_dir=settings.TARGET_DIR,
target_base_url=settings.TARGET_BASE_URL,
refresh_required=False,
session_auth={'https://api.github.com/': HTTPBearerToken(token)}
) No success... Of course, making a standard request (with requests.get) works properly (both token and repo are available). Maybe proxy configuration? Why error involves timestamp.json only? (This is a blocking error, I don't know if any other files are actually found) Is there any way to pass proxy config to the client? Any other suggestions? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
Hi @raffaellof , sorry for the late answer. From the docs:
My first hunch would be an error in the url used for Line 401 in 0283ebb Could you try removing the trailing slash from your code, as follows? session_auth={'https://api.github.com': HTTPBearerToken(token)} Here's the relevant part of the docstring for the Lines 346 to 361 in 0283ebb If that does not help, perhaps it has to do with the permissions for your PAT. Here's a list of required permissions for fine-grained PATs, per API endpoint, and here a list of scopes for classic PATs. Another possible cause for a 404 could arise with classic PAT and SSO, according to the docs:
|
Beta Was this translation helpful? Give feedback.
-
Here I am... much appreciated your help
Sure, I did, it was a typo, my bad
Subclass of requests.auth.AuthBase to add headers like so: class HttpsGitTokenAuth(AuthBase):
"""Subclass of requests.auth.AuthBase to add custom headers"""
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['authorization'] = f'Bearer {self.token}'
r.headers['accept'] = 'application/vnd.github.raw+json'
r.headers['X-GitHub-Api-Version'] = '2022-11-28'
return r This works for me, when the app runs in a network without proxies
Still facing an error trying downloading files from the repo, when my app runs in a network behind a proxy
Then I followed your advice (thanks for putting me on the right way)
Subclass of tufup.client.AuthRequestsFetcher to add my custom session.proxies (overridden methods init and _get_session) class AuthRequestsFetcherProxyMode(AuthRequestsFetcher):
"""Subclass of tufup.client.AuthRequestsFetcher to add custom proxies configuration"""
def __init__(
self,
session_auth: Optional[Dict[str, Union[Tuple[str, str], AuthBase]]] = None
) -> None:
super().__init__(session_auth=session_auth)
# My custom proxies
self.proxies = { # Same proxy for both protocols
'http': 'http://proxy:port',
'https': 'http://proxy:port'
}
def _get_session(self, url: str) -> requests.Session:
# set the Session.proxies attribute for the specified server, if available
session = super()._get_session(url=url)
session.proxies = self.proxies
return session ...and monkey-patch the tufup.client.Client.init in the simplest way I figured out (context-manager): with mock.patch(target='tufup.client.AuthRequestsFetcher', new=AuthRequestsFetcherProxyMode):
client = Client(
app_name=settings.APP_NAME,
app_install_dir=settings.INSTALL_DIR,
current_version=settings.APP_VERSION,
metadata_dir=settings.METADATA_DIR,
metadata_base_url=settings.METADATA_BASE_URL,
target_dir=settings.TARGET_DIR,
target_base_url=settings.TARGET_BASE_URL,
refresh_required=False,
session_auth={'https://api.github.com': HttpsGitTokenAuth(git_token)}
) ...client object initialized successfully! Unfortunately I didn't solve the problem... and i don't know why! When my app runs behind a proxy and checks for updates, keep logging Failed Download error. I still think something goes wrong in the proxy configuration step, still looking for a fix :( |
Beta Was this translation helpful? Give feedback.
-
@raffaellof Sorry to hear that. Could you post the relevant part of the log, showing the actual "Failed Download" error? |
Beta Was this translation helpful? Give feedback.
-
@raffaellof On a side note, I just found out there's an easier way to configure proxies for You can simply set the environment variables At least this implies you should not need to subclass the It may also help with the download issue. |
Beta Was this translation helpful? Give feedback.
-
I took some time to do some tests... the only way to make my app working properly, even behind a proxy, is by setting environment variables as suggested above. os.environ['HTTP_PROXY'] = f'http://{user}:{password}@{PROXY}:{PORT}'
os.environ['HTTPS_PROXY'] = f'http://{user}:{password}@{PROXY}:{PORT}' P.S. If (as in my case) the proxy requires authorization, credentials should be percent-encoded to avoid conflicts, to do this I used import urllib.parse
user = urllib.parse.quote(user)
password = urllib.parse.quote(password) Problem solved. Thanks for your precious help @dennisvang |
Beta Was this translation helpful? Give feedback.
@raffaellof On a side note, I just found out there's an easier way to configure proxies for
requests
:You can simply set the environment variables
HTTP_PROXY
,HTTPS_PROXY
, etc.At least this implies you should not need to subclass the
AuthRequestsFetcher
.It may also help with the download issue.