fireproofsocks

fireproofsocks

Signing a JWT?

Does anyone have a full working example of signing JWTs? I guess this is partly a question about the process too… this is related to earlier work I did (and this other post).

When you complete a sign-in with Google, you are given a JWT. You can can look up the PEM that was used to sign the key at https://www.googleapis.com/oauth2/v1/certs

And that can be used to verify that the JWT has not been tampered with.

From
https://github.com/danharper/hmac-examples#elixir

There’s this Elixir example:

key = 'the shared secret key here'
message = 'the message to hash here'

signature = :crypto.hmac(:sha256, key, message)

# to lowercase hexits
Base.encode16(signature, case: :lower)

When you’re dealing with a JWT, the message is a Base64 encoding of the JSON header + the JSON claims. But what’s the key in this scenario? When Google lets us query its PEM, what is in that PEM? Is it a private key? A public key? Or a combination? And what gets used to sign the JWT?

I’m writing tests around this stuff, so I need to be able to generate a public + private key, convert them (or one of them?) to PEM format, and then properly sign the key so that the JWT can be properly checked.

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hey @fireproofsocks it’s a private key. Here is code I wrote to validate JWT keys against google firebase pem. You can probably refactor it to grab pems from somewhere else.

First, I had a genserver which, on boot, would fetch the keys from Google and put them in ets:

def request_keys(_) do
    url = keys_url()

    {:ok, 200, headers, body} = :hackney.request(:get, url, [], "", [:with_body])

    {_, cache_control} =
      Enum.find(headers, fn {k, _} ->
        String.downcase(k) == "cache-control"
      end)

    [_, expire_in] = Regex.run(~r/max\-age\=([0-9]*),/, cache_control)
    expire_in = String.to_integer(expire_in)

    body
    |> Jason.decode!()
    |> Map.values()
    |> Enum.map(&JOSE.JWK.from_pem/1)
    |> Enum.map(fn key ->
      %{type: :firebase, key: key, expire_in: expire_in * 1000}
    end)
  end

  defp keys_url() do
    "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
  end

That’s the fetching and parsing code, the ets and refresh based on expires in is left as an exercise to the reader.

In any case once that’s in place, when a request comes in with a JWT key you can verify it via:

def verify(token) do
    [{:keys, keys}] = :ets.lookup(Maven.Accounts.Auth, :keys)

    Enum.find_value(keys, &do_verify(&1, token))
  end

  defp do_verify(key_data, token) do
    case JOSE.JWT.verify(key_data.key, token) do
      {true, %{fields: fields}, _} ->
        {:ok, key_data.type, fields}

      _ ->
        nil
    end
  end
fireproofsocks

fireproofsocks

Thanks @benwilson512 – this is a clean example of how to verify keys, cleaner than what I had worked out. However, I was looking for how to sign the key. @danschultzer – I think AssentJWT.sign/3 does exactly what I want. Thank you!

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hi @enkr1, please provide samples of the code you are running, and the resources you’ve tried to follow. We can’t help if you don’t show us what you’ve tried so far.

Last Post!

enkr1

enkr1

I also tried this guy’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"}
 }}

I have just created a new thread: How to verify RS256 JWT with Joken.Signer.verify/2 - 2022

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 131117 1222
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New

We're in Beta

About us Mission Statement