pedrocaseiro

pedrocaseiro

How to implement Apple Login in a Phoenix app?

Hey everyone!
I’m currently implementing sign in with apple on my app. I’m already at the point where I got the JWT that I need to decode to validate the user and the key hash from apple (includes the kid, the alg etc…
How can I use the information from the key hash to decode the JWT correctly?
In Ruby it seems pretty straight forward with

keyHash = ActiveSupport::HashWithIndifferentAccess.new(apple_certificate["keys"].select {|key| key["kid"] == kid}[0])
jwk = JWT::JWK.import(keyHash)
token_data = JWT.decode(jwt, jwk.public_key, true, {algorithm: alg})[0]

But I’m having a hard time finding the equivalent in Elixir. I took a look at JOSE.JWK but I’m not sure which method I should use to generate the JWK and fetch the public key afterward
Thanks!

Most Liked

Udi

Udi

defmodule Accounts.AppleAuth do
  @apple_keys_url "https://appleid.apple.com/auth/keys"
  @aud "com.blahblah"

  def verify_identity_token(identity_token) do
    # Fetch Apple's public keys
    case get_apple_public_keys() do
      {:ok, apple_keys} ->
        with {:ok, token} <- decode_and_verify(identity_token, apple_keys) do
          verify_claims(token)
        end

      {:error, reason} ->
        {:error, reason}
    end
  end

  defp get_apple_public_keys() do
    case HTTPoison.get(@apple_keys_url) do
      {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
        case Jason.decode(body) do
          {:ok, %{"keys" => keys}} ->
            {:ok, keys}
          {:error, _} ->
            {:error, "Failed to decode Apple's public keys"}
        end

      {:ok, %HTTPoison.Response{status_code: status_code}} ->
        {:error, "Failed to fetch Apple's public keys, status code: #{status_code}"}

      {:error, %HTTPoison.Error{reason: reason}} ->
        {:error, "HTTP request failed: #{reason}"}
    end
  end

  defp decode_and_verify(token, apple_keys) do
    # Find the appropriate key for the token
    key = find_apple_key(token, apple_keys)

    if key do
      jwk = JOSE.JWK.from(key)
      {verified, jwt, _} = JOSE.JWT.verify_strict(jwk, ["RS256"], token)
      if verified, do: {:ok, jwt}, else: {:error, "Invalid token signature"}
    else
      {:error, "No matching key found"}
    end
  end

  defp verify_claims(jwt) do
    %JOSE.JWT{fields: claims} = jwt

    case claims do
      %{"aud" => @aud, "exp" => exp} ->
        current_time = System.system_time(:second)

        if exp > current_time do
          {:ok, claims}
        else
          {:error, "Token has expired"}
        end

      _ ->
        {:error, "Invalid claims"}
    end
  end

  defp find_apple_key(token, keys) do
    # Decode token header to find matching `kid`
    %JOSE.JWS{fields: %{"kid" => kid}} = JOSE.JWT.peek_protected(token)
    Enum.find(keys, fn key -> key["kid"] == kid end)
  end
end

The above seems to be working for me! Hope it helps someone out one day.

jayden

jayden

I recently implemented Sign in with Apple in our app, and I used Joken to handle both token verification and client secret generation.

Here’s what I did to decode the JWT (Note: My example uses Joken v1.5)

token = Joken.token(id_token)
%{"alg" => alg, "kid" => key_id} = Joken.peek_header(token)

token
|> Joken.with_signer(Signer.rs(alg, public_key))
|> Joken.with_validation("aud", &(&1 == "<client_id>"))
|> Joken.with_validation("exp", &(&1 >= System.os_time(:second)))
|> Joken.with_validation("iss", &(&1 == "<issuer>"))
|> Joken.verify!()

public_key above is the matching key fetched from Apple’s public key endpoint.

Hope this helps - and feel free to reach out with additional questions

JeyHey

JeyHey

With Assent it is very easy too (in my mix file: {:assent, "~> 0.1.13"}). You just have to pass the apple authorization code (ASAuthorizationAppleIDCredentialauthorizationCode) and the apple_id is then verified. No need to manually pass the public key and algorithm. You don’t even need to pass the identityToken:

def check_apple_sign_in(_apple_jwt, apple_auth) do
    [
     client_id: "com.your_domain.your_app",
     team_id: "YOUR_ID",
     private_key_id: "KEY_ID",
     private_key_path: "/Users/you/development/Keys/AuthKey_2YZ4LV4PYI.p8",
     redirect_uri: nil
    ]
    |> Assent.Config.put(:session_params, %{})
    |> Assent.Strategy.Apple.callback(%{"code" => apple_auth})
    |> case do
      {:ok, %{user: user, token: token}} ->
        %{"sub" => user_id} = user
        Logger.info "apple sign in verification successful. user: #{Kernel.inspect(user)}; token: #{Kernel.inspect(token)}"
        {:ok, user_id} #the user_id you are interested in
      error ->
        Logger.info "apple sign in verification not successful: #{Kernel.inspect(error)}"
        {:error, :authentication}
    end
  end

Where Next?

Popular in Questions Top

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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
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

We're in Beta

About us Mission Statement