How to get a GCP Bearer token programmatically with python

前端 未结 5 1269
余生分开走
余生分开走 2020-12-02 23:37

gcloud auth print-access-token gives me a Bearer token that I can use later on; however, this is a shell command. How would I obtain one programmatically via t

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 00:13

    import google.auth
    import google.auth.transport.requests
    
    
    # getting the credentials and project details for gcp project
    credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
    
    #getting request object
    auth_req = google.auth.transport.requests.Request()
    
    print(credentials.valid) # prints False
    credentials.refresh(auth_req) #refresh token
    #cehck for valid credentials
    print(credentials.valid)  # prints True
    print(credentials.token) # prints token
    

提交回复
热议问题