Search code examples
erlanggoogle-oauthjwtsha256rsa-sha256

Computing the JWT signature for Google OAuth Service Account using erlang?


I have created google service account and have JSON file containing private_key, client_email etc.

JWT should be created to get access token.

I have followed following step

Header computation:

Header = jsx:encode(#{<<"alg">> => <<"RS256">>,<<"typ">> => <<"JWT">>}).
Base64Header = base64:encode(Header).

Claims computation:

Claims = jsx:encode(#{
  <<"iss">> => <<"[email protected]">>,
  <<"scope">> => <<"https://www.googleapis.com/auth/cloud-platform">>,
  <<"aud">> => <<"https://www.googleapis.com/oauth2/v4/token">>,
  <<"exp">> => 1471629262,
  <<"iat">> => 1471627282
}).
Base64Claims = base64:encode(Claims).


Input = {Base64Header}.{Base64Claim}

And, How we can sign the UTF-8 representation of the Input using SHA256withRSA (also known as RSASSA-PKCS1-V1_5-SIGN with the SHA-256 hash function) with the private_key to compute JWT Signature?


Solution

  • There are libraries already built to do this. One (which I am using) is Erlang JOSE.

    %% In OTP 17 or later
    Signed = jose_jwt:sign(RSAPrivate, #{ <<"alg">> => <<"RS256">> }, Payload),
    {_JWS, Token} = jose_jws:compact(Signed).