How to verify RS256 JWT with Joken.Signer.verify/2 - 2022

Hi community,

I am trying to verify the JWT with my public key (.pem) before decrypting it, and then proceeding to process the payload.

Similar to Joken: Using Joken.verify - trying to verify with a RS256 public key

I have tried to read through the documentation, but there are not many efficient examples.

Here is how I did it:

return_token = "eyJhb...."

case File.read("./public.pem") do
  {:ok, public_key} ->
    {_, %{"n" => n} = key_map} =
      JOSE.JWK.from_pem(public_key) 
      |> JOSE.JWK.to_map() 

    signer =
      Joken.Signer.create("RS256", key_map)
      |> IO.inspect(label: "signer")

    Joken.Signer.verify(return_token, signer)
    |> IO.inspect(label: "verify") # Here is the part where it gives error

  {:error, unsupported_case} ->
    unsupported_case |> IO.inspect(label: "i didnt expect this.")
    {:erorr, "Something went wrong while trying to read the public.pem ..."}
end

output:

# ...
signer: %Joken.Signer{
  jwk: %JOSE.JWK{
    keys: :undefined,
    kty: {:jose_jwk_kty_rsa,
     {:RSAPublicKey,
 2374353...43,
      65537}},
    fields: %{}
  },
  jws: %JOSE.JWS{
    alg: {:jose_jws_alg_rsa_pkcs1_v1_5, :RS256},
    b64: :undefined,
    fields: %{"typ" => "JWT"}
  },
  alg: "RS256"
}

verify: {:error, :signature_error}
# ...

I also tried this @vinagrito1’s solution Using Joken to validate Google JWTs - #12 by vinagrito1

but what I am getting is false instead of true:

{false,
 %JOSE.JWT{
   fields: %{
      # ...
   }
 },
 %JOSE.JWS{
   alg: {:jose_jws_alg_rsa_pkcs1_v1_5, :RS256},
   b64: :undefined,
   fields: %{"typ" => "JWT"}
 }}

Thank you so much in advance.

Best,
Jing Hui P.

Facing similar issue with Joken. The result is always false when I trying with azure access token but it works fine for id token from azure.

Any reason why we can’t verify the access token signature to be valid?

1 Like