如何通过http获取$(gcloud auth print-access-token)这个gcloudaccess-token值?
不安装gcloud如何才能获取这个access-token?
https://cloud.google.com/sdk/docs/install?hl=zh-cn
网友回复
gcloud access-token这个值谷歌cloud官方是通过gcloud 的客户端命令行获取的,需要下载到本地运行后获取
当然也有人根据这套协议写出了不需要命令行的代码,模拟了命令行的执行:
我们以cloudflare的worker为例,其他的编程语言可以通过ai更换:
// 配置变量 const PROJECT_ID = ''; const CLIENT_EMAIL = ''; const PRIVATE_KEY =""; addEventListener("fetch", (event) => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { const [token, err] = await exchangeJwtForAccessToken(signedJWT) if (token === null) { console.log(`Invalid jwt token: ${err}`) return createErrorResponse(500, "api_error", "invalid authentication credentials"); } } function createErrorResponse(status, errorType, message) { const errorObject = { type: "error", error: { type: errorType, message: message } }; return new Response(JSON.stringify(errorObject), { status: status, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }); } async function createSignedJWT(email, pkey) { pkey = pkey.replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\r|\n|\\n/g, ""); let cryptoKey = await crypto.subtle.importKey( "pkcs8", str2ab(atob(pkey)), { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" }, }, false, ["sign"] ); const authUrl = "https://www.googleapis.com/oauth2/v4/token"; const issued = Math.floor(Date.now() / 1000); const expires = issued + 600; const header = { alg: "RS256", typ: "JWT", }; const payload = { iss: email, aud: authUrl, iat: issued, exp: expires, scope: "https://www.googleapis.com/auth/cloud-platform", }; const encodedHeader = urlSafeBase64Encode(JSON.stringify(header)); const encodedPayload = urlSafeBase64Encode(JSON.stringify(payload)); const unsignedToken = `${encodedHeader}.${encodedPayload}`; const signature = await crypto.subtle.sign( "RSASSA-PKCS1-v1_5", cryptoKey, str2ab(unsignedToken) ); const encodedSignature = urlSafeBase64Encode(signature); ret...
点击查看剩余70%