Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Verify user's ID token generated via firebase client. Bump version 0.2.1 #8

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

aniruddhasd
Copy link

Added functionality to verify id token generated by Firebase Auth.
Based on configuration, the library picks the corresponding firebase project and verifies all necessary params against it.
Optionally force checking of email_verified key.

@@ -5,6 +5,7 @@ defmodule FirebaseAdminEx.Auth do
@auth_endpoint "https://www.googleapis.com/identitytoolkit/v3/relyingparty/"
@auth_endpoint_account "https://identitytoolkit.googleapis.com/v1/projects/"
@auth_scope "https://www.googleapis.com/auth/cloud-platform"
@auth_cert_url "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i worked on something similar, can you check this code, maybe you can use it

Suggested change
@auth_cert_url "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
@public_keys "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
@header_claims ["alg", "kid", "typ"]
@payload_claims ["exp", "iat", "aud", "iss", "sub", "auth_time"]
@doc """
Verifica si un token jwt de firebase es válido
"""
@spec verify_id_token(String.t()) :: tuple
def verify_id_token(token) do
with [header, payload, _signature] <- String.split(token, ".") do
# Certificados y llaves públicas de google
public_keys =
@public_keys
|> HTTPoison.get!()
|> Map.get(:body)
|> Poison.decode!()
# Credenciales para verificar los claims del token
firebase_credentials =
:goth
|> Application.get_env(:json)
|> Poison.decode!()
|> List.last()
# Validar claims del header
valid_header? =
header
|> Base.decode64!(padding: false)
|> Poison.decode!()
|> Map.take(@header_claims)
|> Enum.all?(fn {k, v} ->
_valid_claim?(k, v, public_keys, firebase_credentials)
end)
# Validar claims del payload
valid_payload? =
payload
|> Base.decode64!(padding: false)
|> Poison.decode!()
|> Map.take(@payload_claims)
|> Enum.all?(fn {k, v} ->
_valid_claim?(k, v, public_keys, firebase_credentials)
end)
if valid_header? and valid_payload? do
# Validar si el token jwk fue firmado con la llave privada de google
# haciendo uso de la llave publica
kid =
header
|> Base.decode64!(padding: false)
|> Poison.decode!()
|> Map.get("kid")
cert =
public_keys
|> Map.get(kid)
|> JOSE.JWK.from_pem()
{valid_signature?, claims, _jws} = JOSE.JWK.verify(token, cert)
if valid_signature? do
{:ok, Poison.decode!(claims)}
else
{:error, "La firma del token no es válida"}
end
else
{:error, "El header o el payload del token no es válido"}
end
else
_ -> {:error, "Token no válido"}
end
end
# Valida si los claims del header/payload son válidos
@spec _valid_claim?(String.t(), String.t() | integer, map, map) :: boolean
defp _valid_claim?("alg", "RS256", _, _), do: true
defp _valid_claim?("alg", _, _, _), do: false
defp _valid_claim?("kid", kid, public_keys, _), do: Map.has_key?(public_keys, kid)
defp _valid_claim?("typ", "JWT", _, _), do: true
defp _valid_claim?("typ", _, _, _), do: false
defp _valid_claim?("exp", exp, _, _) do
exp > DateTime.diff(Timex.now(), DateTime.from_unix!(0))
end
defp _valid_claim?("iat", iat, _, _) do
iat < DateTime.diff(Timex.now(), DateTime.from_unix!(0))
end
defp _valid_claim?("aud", aud, _, firebase_credentials) do
aud == Map.get(firebase_credentials, "project_id")
end
defp _valid_claim?("iss", iss, _, firebase_credentials) do
project_id = Map.get(firebase_credentials, "project_id")
iss == "https://securetoken.google.com/#{project_id}"
end
defp _valid_claim?("sub", sub, _, _), do: sub not in ["", nil]
defp _valid_claim?("auth_time", auth_time, _, _) do
auth_time < DateTime.diff(Timex.now(), DateTime.from_unix!(0))
end
# Obtiene los datos del cliente de firebase
@spec _get_client_data(String.t()) :: String.t()
defp _get_client_data(key) do
:goth
|> Application.get_env(:json)
|> Poison.decode!()
|> List.last()
|> Map.get(key)
end

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants