Google cloud platform 用于服务器到服务器应用程序的Google OAuth 2.0
我想从外部访问GCP存储桶。所以我使用了谷歌提供的以下步骤Google cloud platform 用于服务器到服务器应用程序的Google OAuth 2.0,google-cloud-platform,google-cloud-storage,Google Cloud Platform,Google Cloud Storage,我想从外部访问GCP存储桶。所以我使用了谷歌提供的以下步骤 创建服务帐户 使用为服务帐户提供的私钥生成jwt令牌 当我调用上面的API通过提供jwt令牌来获取访问令牌时,它给出了以下错误 { "error": "invalid_scope", "error_description": "Empty or missing scope not allowed." } 提前谢谢 这是我用来生成JWT的Java代码 long now = System.currentTimeMill
{
"error": "invalid_scope",
"error_description": "Empty or missing scope not allowed."
}
提前谢谢
这是我用来生成JWT的Java代码
long now = System.currentTimeMillis();
try {
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("service.json"));
PrivateKey privateKey = credential.getServiceAccountPrivateKey();
String privateKeyId = credential.getServiceAccountPrivateKeyId();
Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
String signedJwt = JWT.create()
.withKeyId(privateKeyId)
.withIssuer("***********@************-******.iam.gserviceaccount.com")
.withSubject("***********@************-******.iam.gserviceaccount.com")
.withAudience("https://www.googleapis.com/oauth2/v4/token")
.withIssuedAt(new Date(now))
.withExpiresAt(new Date(now + 3600 * 1000L))
.sign(algorithm);
System.out.println(signedJwt);
} catch(Exception e) {
System.out.println(e);
}
我明白了这个问题。我通过传递有效负载来生成JWT令牌。 下面是我用来生成jwt令牌的python代码。 我从下面的python代码中获得了参考
import jwt
import time
# Permissions to request for Access Token
scopes = "https://www.googleapis.com/auth/devstorage.read_write"
# private key id
pkey_id = ""
# private key
pkey = ""
serviceid = ""
# Google Endpoint for creating OAuth 2.0 Access Tokens from Signed-JWT
auth_url = "https://www.googleapis.com/oauth2/v4/token"
# Set how long this token will be valid in seconds
expires_in = 3600 # Expires in 1 hour
issued = int(time.time())
expires = issued + expires_in # expires_in is in seconds
# JWT Payload
payload = {
"iss": serviceid, # Issuer claim
"sub": serviceid, # Issuer claim
"aud": auth_url, # Audience claim
"iat": issued, # Issued At claim
"exp": expires, # Expire time
"scope": scopes # Permissions
}
# JWT Headers
additional_headers = {
'kid': pkey_id,
"alg": "RS256",
"typ": "JWT" # Google uses SHA256withRSA
}
sig = jwt.encode(payload, pkey, algorithm="RS256", headers=additional_headers)
print(sig)
显示有关如何创建签名JWT和指定作用域的代码。我写了一篇文章,详细介绍了如何使用Python从服务帐户创建访问令牌:@JohnHanley这是我如何生成jwt令牌的。编辑您的问题并格式化您的代码,以便我们阅读。@JohnHanley非常感谢您的帮助。我仔细阅读了你的文章并找出了问题所在。你可以通过GCP IAM&Admin>service account>Create key(操作列)为给定的服务id生成私钥id和私钥(pkey\u id,pkey)