Skip to content
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

Feature request: Google Cloud Auth #59

Open
aebrahim opened this issue Jan 12, 2023 · 0 comments
Open

Feature request: Google Cloud Auth #59

aebrahim opened this issue Jan 12, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@aebrahim
Copy link

aebrahim commented Jan 12, 2023

Sample code below provided under MIT and Apache 2.0 licenses. This runs and works on your computer if you install the gcloud cli and run gcloud auth login

import asyncio
import threading

import google.auth.transport.requests
import google.auth
import httpx


class GoogleAuth(httpx.Auth):
    """Adds required authorization for requests to Google Cloud Platform.

    This gets the default credentials for the running user, and uses them to
    generate valid tokens to attach to requests.
    """

    def __init__(self, scopes=("https://www.googleapis.com/auth/cloud-platform",)):
        self._sync_lock = threading.RLock()
        self._async_lock = asyncio.Lock()
        self.scopes = scopes
        self.creds = None

    def _refresh_creds(self):
        # Must only be called with a lock.
        if self.creds is None:
            self.creds, _ = google.auth.default(scopes=self.scopes)
        auth_req = google.auth.transport.requests.Request()
        self.creds.refresh(auth_req)

    def sync_auth_flow(self, request: httpx.Request):
        if self.creds is None or self.creds.expired:
            with self._sync_lock:
                self._refresh_creds()
        request.headers["Authorization"] = "Bearer " + self.creds.token
        yield request

    async def async_auth_flow(self, request: httpx.Request):
        if self.creds is None or self.creds.expired:
            async with self._async_lock:
                await asyncio.to_thread(self._refresh_creds)
        request.headers["Authorization"] = "Bearer " + self.creds.token
        yield request


client = httpx.Client(auth=GoogleAuth())
response = client.get("https://cloudresourcemanager.googleapis.com/v1/projects")
print(response.json())
@Colin-b Colin-b added the enhancement New feature or request label Dec 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants