3 storage curl blob google-cloud-storage google-cloud-platform
我正在尝试使用这里解释的curl请求从云存储桶下载文件 - https://cloud.google.com/storage/docs/downloading-objects#download-object-json
在上面的文档中,在第 1 步中,我看到访问令牌是从Oauth 2.0 Playground生成的。但是,我想以编程方式生成令牌并发送 CURL 请求。\
有没有办法通过任何脚本获取访问令牌?可能来自使用服务帐户的另一个 CURL 请求?
用于服务器到 google 服务器应用程序的 Bash OAuth 2.0 JWT 脚本
#1. Create a service account with storage permissions to download the objects and download the p12 key file
#2. Convert p12 key to pem
PRIVATE_KEY=privateKey.pem
openssl pkcs12 -in privatekey.p12 -nodes -nocerts --passin pass:notasecret > $PRIVATE_KEY
#3. Create an object and uploaded to storage
cat file
#This is a testing file
gsutil cp file gs://your-bucket/
#4.Create a JSON Web Token (JWT, pronounced, "jot") which includes a header, a claim set, and a signature.
ALG=RS256
TYP=JWT
JSON_HEADER=$( jq -n --arg alg "$ALG" --arg typ "$TYP" '{alg: $alg, typ: $typ}' )
JSON_HEADER_ENCODED=`echo -n $JSON_HEADER | openssl base64 -e`
ISS=user@project.iam.gserviceaccount.com
SCOPE=https://www.googleapis.com/auth/cloud-platform
AUD=https://oauth2.googleapis.com/token
IAT=$(date +%s)
EXP=$(($IAT + 3600))
JSON_CLAIM=$( jq -n --arg iss "$ISS" --arg scope "$SCOPE" --arg aud "$AUD" --arg exp "$EXP" --arg iat "$IAT" '{iss: $iss, scope: $scope, aud: $aud, exp: $exp, iat: $iat}');
JSON_CLAIM_ENCODED=`echo -n $JSON_CLAIM | openssl base64 -e`
HEAD_AND_CLAIM_TR=`echo -n "$JSON_HEADER_ENCODED.$JSON_CLAIM_ENCODED" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`
echo $HEAD_AND_CLAIM_TR
SIGNATURE_ENCODED=`echo -n "$HEAD_AND_CLAIM_TR" | openssl dgst -sha256 -sign $PRIVATE_KEY | openssl base64 -e`
SIGNATURE_TR=`echo -n "$SIGNATURE_ENCODED" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`
echo $SIGNATURE_TR
JWT_ASSERTION="$HEAD_AND_CLAIM_TR.$SIGNATURE_TR"
echo $JWT_ASSERTION
#5. Request an access token from the Google OAuth 2.0 Authorization Server.
RESPONSE=`curl -H "Content-type: application/x-www-form-urlencoded" -X POST "https://oauth2.googleapis.com/token" -d \
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$JWT_ASSERTION" `
#6. Handle the JSON response that the Authorization Server returns.
BEARER=`echo $RESPONSE | jq '.access_token'`
#7. Download the object from GCS
curl -X GET \
-H "Authorization: Bearer $BEARER" \
-o "test_file" \
"https://storage.googleapis.com/storage/v1/b/your-bucket/o/file?alt=media"
#8. Test it
cat test_file
#This is a testing file
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10683 次 |
| 最近记录: |