Search…
generate_jwt
The generate_jwt statement is used to generate an RFC 7515-compliant JWT (JSON Web Token) which can be used, for example, for Google Cloud OAuth 2.0 Server to Server Authentication.

Syntax

generate_jwt keykey component1 [... componentN]asresult

Details

The generate_jwt statement performs the following actions:
    encodes all components as Base64URL
    concatenates all components using a dot separator (.)
    hashes the concatenated result using SHA256
    signs the hash with a provided PEM-encoded key using the RSA algorithm
    encodes the resulting signature as Base64URL
    builds JWT by concatenating the two results using a dot separator (.)
    stores the final result in th variable specified by the result parameter
The RSA key needs to be in PEM format. PEM format requires the header and footer to be on separate lines so it is important to separate the key contents with ${NEWLINE}as shown below:
var key = "-----BEGIN PRIVATE KEY-----${NEWLINE}Key-data-goes-here{$NEWLINE}-----END PRIVATE KEY-----"

Example

To acquire a Google Cloud OAuth 2.0 access token:
1
var private = "-----BEGIN PRIVATE KEY-----${NEWLINE}key goes here${NEWLINE}-----END PRIVATE KEY-----"
2
var email = "[email protected]"
3
var url = "https://www.googleapis.com/oauth2/v4/token"
4
var scope = "https://www.googleapis.com/auth/cloud-platform"
5
6
var now = ${UNIX_UTC}
7
var expiry = (${now} + 3600)
8
9
var header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"
10
var payload = "{\"iss\":\"${email}\",\"scope\":\"${scope}\",\"aud\":\"${url}\",\"iat\":\"${now}\",\"exp\":\"${expiry}\"}"
11
12
generate_jwt key ${private} ${header} ${payload} as JWT
13
14
# Make HTTP request according to https://developers.google.com/identity/protocols/OAuth2ServiceAccount
15
set http_header "Content-Type: application/x-www-form-urlencoded"
16
set http_body data "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=${JWT}"
17
buffer token = HTTP POST "${url}"
18
19
if (${HTTP_STATUS_CODE} != 200) {
20
print Got HTTP status ${HTTP_STATUS_CODE}, expected a status of 200
21
print The server response was:
22
json format {token}
23
print {token}
24
terminate
25
}
26
27
var access_token = $JSON{token}.[access_token]
28
print Access token: ${access_token}
Copied!
Last modified 1yr ago
Export as PDF
Copy link