'Get OAuth 2.0 token for google service accounts

Short explanation I want to get a Auth2.0 token for access to some APIs in my Google Cloud Platform proyect.

Context At the current time i have a Wordpress page that has to make the connection. Temporarily i will make a javascript connection with the client via Ajax (when all work successfully i will make this in another way, for example with a PHP server in the middle). The process that has to execute in our GCP don't need the user to log in with his google account, for that reason we will make a google service account for server to server connections. All the threads executed by the API will be log like be executed by this service account that isn't owned by any real person.

When i generate the Ajax connection for get the token, this will be send to the following URL: https://oauth2.googleapis.com/token

I send it on JWT coding. The coded message is generated in this Javascript code: `

var unixHour = Math.round((new Date()).getTime() / 1000);

var header = {
  "alg":"RS256",
  "typ":"JWT"
}
var data = {
  "iss":"[email protected]",
  "scope":"https://www.googleapis.com/auth/devstorage.read_only",
  "aud":"https://oauth2.googleapis.com/token",
  "exp":(unixHour+3600),
  "iat":unixHour
}

var secret = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCkhZH7TuaNO4XBVVVcE2P/hvHSsGXNu1D/FcCaMrW56BF/nbOlxAtbp07TCIOyrR1FEcJb+to66olSFnUVUWhWUB9zLbzKpULQoFmYECSWppUbCZd+bp271AFYZpxXFduziWuaG9BNxV2cmWTjLLlZI7FoIYFwLgPZHPWndY0E99lGEjmnH";

function base64url(source) {
  // Encode in classical base64
  encodedSource = CryptoJS.enc.Base64.stringify(source);
  
  // Remove padding equal characters
  encodedSource = encodedSource.replace(/=+$/, '');
  
  // Replace characters according to base64url specifications
  encodedSource = encodedSource.replace(/\+/g, '-');
  encodedSource = encodedSource.replace(/\//g, '_');
  
  return encodedSource;
}

var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
var encodedHeader = base64url(stringifiedHeader);
//document.getElementById("header").innerText = encodedHeader;
console.log(encodedHeader);

var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
var encodedData = base64url(stringifiedData);
//document.getElementById("payload").innerText = encodedData;
console.log(encodedData);

var signature = encodedHeader + "." + encodedData;
signature = CryptoJS.HmacSHA256(signature, secret);
signature = base64url(signature);
console.log(signature);
//document.getElementById("signature").innerText = signature;

var jwt = encodedHeader + "." + encodedData + "." + signature;
console.log(jwt);
$.ajax({
    url: 'https://oauth2.googleapis.com/token',
    type: 'POST',
    data: { "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion" : jwt} ,
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    success: function (response) {
        alert(response.status);
    },
    error: function () {
        alert("error");
    }
});

`

Console: Console output

The problem The Ajax message generated in the script return "Invalid JWT signature". send message API ajax response API

Following the google documentation, this problem is for a bad coding of the message or a incorrect secret key.

You can see the code for generate the coding message in the previous script. About the secret key, maybe i am not selecting the correct key for this task, here you have the steps i follow: cred GCP Inside the service account, i create a key in the "keys" section: Keys GCP As result this download this file: File keys

I tried to use like secret key the "private_key" content of this file and additionally i tried to delete the line breaks (\n) of this and try again. ¿Is that correct?¿Or i dont use the corret key? ¿Maybe i make an incorrect coding?

*There aren't problems with share the key and account id because the key was disabled at the moment of share this thread and the project is only for testing purposes.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source