Joken errors when trying to create a JWT

Hello good people :slight_smile:

I’m trying to create JWT’s with dynamic config using Joken (i.e I have zero config in my config.exs).

One similar issue I saw was that the person wasn’t sending the token_config to the Joken.generate_and_sign function, but based on various examples you can send an empty map. Or I’m missing something.

Here is my code:

claims = %{}
    |> Joken.Config.add_claim("iss", fn -> iss end, &(&1 == iss))
    |> Joken.Config.add_claim("sub", fn -> iss end, &(&1 == sub))
    |> Joken.Config.add_claim("aud", fn -> iss end, &(&1 == aud))
    |> Joken.Config.add_claim("iat", fn -> iss end, &(&1 == iat))
    |> Joken.Config.add_claim("exp", fn -> iss end, &(&1 == exp))

    signer = Joken.Signer.create("RS256", %{"pem" => key}, %{"kid" => kid})

    {:ok, token, _claims} = Joken.generate_and_sign(%{}, token_config, claims, signer)

    IO.inspect token

FWIW I’m trying to create a token from a Google service_account blob (not file), so…maybe I’m doing it all wrong?

I’d appreciate any help :slight_smile:

Oh, I never added the error…

protocol Enumerable not implemented for %Joken.Signer{alg: "RS256", jwk: %JOSE.JWK{fields: %{}, keys: :undefined, kty: {:jose_jwk_kty_rsa, {:RSAPrivateKey, :"two-prime", ... of type Joken.Signer (a struct)

Haven’t researched that library but it seems that something is trying to iterate on that struct and falls because it’s not a list.

Yeah it looks like Joken.generate_and_sign expects the signer arg to be the third argument and you have fourth:

generate_and_sign(token_config, extra_claims \\ %{}, signer_arg \\ :default_signer, hooks \\ [])

generate_and_sign(token_config(), claims(), signer_arg(), [module()]) ::
  {:ok, bearer_token(), claims()} | {:error, error_reason()}

The map you’re putting in the first argument doesn’t seem to be necessary, maybe?

1 Like

Thanks I figured it out eventually, heh. I turned the claims into a simple map, and then used this:

signer = Joken.Signer.create("RS256", %{"pem" => key})
{:ok, token, _claims} = Joken.encode_and_sign(claims, signer)

Worked fine, got my token, could finally go sleep :wink:

1 Like