如何使用python以编程方式获取GCP Bearer令牌 [英] How to get a GCP Bearer token programmatically with python

查看:135
本文介绍了如何使用python以编程方式获取GCP Bearer令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcloud auth print-access-token给了我一个Bearer令牌,以后可以使用;但是,这是一个shell命令.如何通过Google Cloud Python API以编程方式获取一个?

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 the Google Cloud Python API?

我看到了以前的示例 ="https://oauth2client.readthedocs.io/en/latest/" rel ="noreferrer"> oauth2client ,但现在不推荐使用oauth2client.我该如何使用 google.auth

I see a prior example using oauth2client, but oauth2client is now deprecated. How would I do this with google.auth and oauthlib?

推荐答案

答案取决于您的环境以及您如何创建/获取凭据.

The answer depends on your environment and how you want to create / obtain credentials.

什么是Google Cloud凭据?

Google Cloud凭据是OAuth 2.0令牌.该令牌至少具有Access Token以及可选的Refresh TokenClient ID Token和支持参数,例如expirationService Account EmailClient Email等.

Google Cloud credentials are an OAuth 2.0 token. This token has at a minimum an Access Token and optionally a Refresh Token, Client ID Token, and supporting parameters such as expiration, Service Account Email or Client Email, etc.

Access Token是Google Cloud API中的重要项目.该令牌授权访问云.此令牌可以在诸如curl的程序,诸如python的软件等中使用,并且不需要SDK. Access Token用于HTTP Authorization标头中.

The important item in Google Cloud APIs is the Access Token. This token is what authorizes access to the cloud. This token can be used in programs such as curl, software such as python, etc and does not require an SDK. The Access Token is used in the HTTP Authorization header.

什么是访问令牌?

访问令牌是Google生成的不透明值,它是从Signed JWT(更正确地称为JWS)派生而来的. JWT由标头和声明(有效负载)Json结构组成.这两个Json结构是使用服务帐户的私钥签名的.这些值经过base64编码并连接起来以创建访问密钥.

An access token is an opaque value generated by Google that is derived from a Signed JWT, more correctly called JWS. A JWT consists of a header and claims (the payload) Json structures. These two Json structures are signed with the Service Account's Private Key. These values are base64 encoded and concatenated to create the Access Key.

访问令牌的格式为:base64(header) + '.' + base64(payload) + '.' + base64(signature).

这是一个JWT示例:

标题:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "42ba1e234ac91ffca687a5b5b3d0ca2d7ce0fc0a"
}

有效载荷:

{
  "iss": "myservice@myproject.iam.gserviceaccount.com",
  "iat": 1493833746,
  "aud": "myservice.appspot.com",
  "exp": 1493837346,
  "sub": "myservice@myproject.iam.gserviceaccount.com"
}

使用访问令牌:

将启动虚拟机实例的示例.替换PROJECT_ID,ZONE和INSTANCE_NAME.此示例适用于Windows.

Example that will start a VM instance. Replace PROJECT_ID, ZONE and INSTANCE_NAME. This example is for Windows.

curl -v -X GET -H "Authorization: Bearer <access_token_here>" ^
https://www.googleapis.com/compute/v1/projects/%PROJECT_ID%/zones/%ZONE%/instances/%INSTANCE_NAME%/start

Compute Engine服务帐户:

在这种情况下,达斯汀的答案是正确的,但为了完整起见,我将包括一些其他信息.

Dustin's answer is correct for this case, but I will include for completeness with some additional information.

这些凭据由GCP自动为您创建,并从VM实例元数据中获取.权限由Google控制台中的Cloud API access scopes控制.

These credentials are automatically created for you by GCP and are obtained from the VM Instance metadata. Permissions are controlled by Cloud API access scopes in the Google Console.

但是,这些凭据有一些限制.要修改凭据,您必须首先停止VM实例.此外,并非所有权限(角色)都受支持.

However, these credentials have some limitations. To modify the credentials you must stop the VM Instance first. Additionally, not all permissions (roles) are supported.

from google.auth import compute_engine

cred = compute_engine.Credentials()

服务帐户凭据:

直到您了解凭据的所有类型及其用例,这些凭据将用于除gcloudgsutil之外的所有内容.了解这些凭据将使编写程序时使用Google Cloud变得更加简单.从Google服务帐户Json文件中获取凭证很容易.唯一需要注意的是凭据过期(通常为60分钟),并且需要刷新或重新创建.

Until you understand all of the types of credentials and their use cases, these are the credentials that you will use for everything except for gcloud and gsutil. Understanding these credentials will make working with Google Cloud much simpler when writing programs. Obtaining credentials from a Google Service Account Json file is easy. The only item to make note of is that credentials expire (typically 60 minutes) and either need to be refreshed or recreated.

gcloud auth print-access-token.服务帐户凭据是Google推荐的方法.

gcloud auth print-access-token is NOT recommended. Service Account Credentials are the recommended method by Google.

这些凭据是由控制台,gcloud或通过程序/API创建的.权限由IAM分配给信用凭证,并在Compute Engine,App Engine,Firestore,Kubernetes等以及Google Cloud之外的其他环境中起作用.这些凭证是从Google Cloud下载的,并存储在Json文件中.注意scopes参数.这定义了授予结果凭证对象的权限.

These credentials are created by the Console, gcloud or via programs / APIs. Permissions are assigned to the creditials by IAM and function inside Compute Engine, App Engine, Firestore, Kubernetes, etc. as well as other environments outside of Google Cloud. These credentials are downloaded from Google Cloud and stored in a Json file. Notice the scopes parameter. This defines permissions that are granted to the resulting credentials object.

SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'service-account-credentials.json'

from google.oauth2 import service_account

cred = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)

Google OAuth 2.0凭据:

这些凭据来自完整的OAuth 2.0流.这些凭据是在您启动浏览器以访问Google帐户以授权访问时生成的.此过程要复杂得多,需要大量代码才能实现,并且需要内置的Web服务器来进行授权回调.

These credentials are derived from a full OAuth 2.0 flow. These credentials are generated when your browser is launched to access Google Accounts for authorizing access. This process is much more complicated and requires a fair amount of code to implement and requires a built-in web server for the callback for authorization.

此方法提供了其他功能,例如能够在浏览器中运行所有内容,例如,您可以创建云存储文件浏览器,但是请务必了解安全隐患.此方法是用于支持Google登录等的技术.我喜欢使用此方法在允许用户在网站上发布信息之前对用户进行身份验证.使用正确授权的OAuth 2.0身份和范围的可能性是无限的.

This method provides additional features such as being able to run everything in a browser, example you can create a Cloud Storage File Browser, but be careful that you understand the security implications. This method is the technique used to support Google Sign-In, etc. I like to use this method to authenticate users before allowing posting on websites, etc. The possibilities are endless with correctly authorized OAuth 2.0 identities and scopes.

使用google_auth_oauthlib的示例代码:

Example code using google_auth_oauthlib:

from google_auth_oauthlib.flow import InstalledAppFlow

flow = InstalledAppFlow.from_client_secrets_file(
    'client_secrets.json',
    scopes=scope)

cred = flow.run_local_server(
    host='localhost',
    port=8088,
    authorization_prompt_message='Please visit this URL: {url}',
    success_message='The auth flow is complete; you may close this window.',
    open_browser=True)

使用requests_oauthlib库的示例代码:

Example code using the requests_oauthlib library:

from requests_oauthlib import OAuth2Session

gcp = OAuth2Session(
        app.config['gcp_client_id'],
        scope=scope,
        redirect_uri=redirect_uri)

# print('Requesting authorization url:', authorization_base_url)

authorization_url, state = gcp.authorization_url(
                        authorization_base_url,
                        access_type="offline",
                        prompt="consent",
                        include_granted_scopes='true')

session['oauth_state'] = state

return redirect(authorization_url)


# Next section of code after the browser approves the request

token = gcp.fetch_token(
            token_url,
            client_secret=app.config['gcp_client_secret'],
            authorization_response=request.url)

这篇关于如何使用python以编程方式获取GCP Bearer令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆