Reputation: 113
I wanted to access GCP storage bucket from outside. So I used following steps which google has provided.
When I called the above API to get access token by providing jwt token it gives following error.
{
"error": "invalid_scope",
"error_description": "Empty or missing scope not allowed."
}
Thanks in advance!
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
This is the Java code I used to generate the JWT
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);
}
Upvotes: 1
Views: 459
Reputation: 113
I figure out the issue. It was with the payload that I passed to generate the JWT token. Below I attched the python code which I used to genarate jwt token. I got the reference from https://www.jhanley.com/google-cloud-creating-oauth-access-tokens-for-rest-api-calls/ below python code
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)
Upvotes: 2