Comments (2)
@noizu The API is still a little clunky (I couldn't find any reference anywhere for the "standard" that the firebase keys are in. The kid
appears to be a SHA-1 hash of something, but I'm not sure what has been hashed), but here's how you might accomplish a key verification (I'm just using :httpc
because it's already included in OTP, but HTTPotion
would also work).
["Bearer " <> token] = get_req_header(conn, "authorization")
kid =
try do
token
|> JOSE.JWS.peek_protected()
|> JOSE.decode()
|> Map.get("kid")
catch
_, _ ->
nil
end
{:ok, {{_, 200, _}, _, body}} = :httpc.request(:get, {'https://www.googleapis.com/robot/v1/metadata/x509/[email protected]', []}, [autoredirect: true], [])
firebase_keys = JOSE.JWK.from_firebase(IO.iodata_to_binary(body))
case Map.get(firebase_keys, kid) do
jwk=%JOSE.JWK{} ->
verified = JOSE.JWT.verify_strict(jwk, ["RS256"], token)
_ ->
# handle invalid token or kid
end
from erlang-jose.
Yes, google kind of decided to go it alone in their implementation instead of following best practices .etc. Which is kind of how google seems to operate these days. Too many PHDs not enough engineers.
The token is base64 encoded with the first part indicating the current kid being used, they provide an api with current keys which slowly rotate over some period of time. Aka they return ~4 or so keys and i assume eventually dequeue and queue off the old and new keys so that there's a hour or so window in which you'll be able to look up the key.
I use rather inelegant hack of the uberauth verify_headers behaviour to handle authorization. Although I'll need to clean this up to take advantage of your latest revision.
If anyone else finds themselves dealing with googles nonsense this is what I currently use (worts and all). (I keep keys cached to avoid the need to constantly ping google's endpoint per request with some cache busting logic and rate limiting threshold of 5 seconds to avoid a disfavored or misconfigured user from being able to cause my backend to endlessly request key updates.
I'll follow up when I get the chance to refactor this a bit more to help anyone else down the road that has to handle firebase auth from elixir.
defmodule Ingressor.Plug.VerifyFirebaseHeader do
@moduledoc """
"""
@googleCertificateUrl "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]"
defp fetch_firebase_keys do
request = HTTPotion.get(@googleCertificateUrl)
expire = Timex.parse!(request.headers["expires"], "{RFC1123}")
%{expire: expire, retrieved: DateTime.utc_now(), keys: Poison.decode!(request.body)}
end
defp fetch_firebase_keys_cache(refresh \\ false) do
case :ets.lookup(:firebase_keys, :cache) do
[{:cache, entry}] ->
if (refresh) do
shift = case refresh do
{unit, offset} -> [{unit, offset}]
_ -> [{:minutes, 5}]
end
expires = entry.retrieved |> Timex.shift(shift)
if (DateTime.compare(expires, DateTime.utc_now()) == :gt) do
entry.keys
else
entry = fetch_firebase_keys()
:ets.insert(:firebase_keys, {:cache, entry})
entry.keys
end
else
if (DateTime.compare(entry.expire, DateTime.utc_now()) == :gt) do
entry.keys
else
entry = fetch_firebase_keys()
:ets.insert(:firebase_keys, {:cache, entry})
entry.keys
end
end
[] ->
entry = fetch_firebase_keys()
:ets.insert(:firebase_keys, {:cache, entry})
entry.keys
end
end
defp fetch_firebase_key(encoding_key) do
keys = fetch_firebase_keys_cache()
case (keys[encoding_key] || (fetch_firebase_keys_cache(true))[encoding_key] || (fetch_firebase_keys_cache({:seconds, 5}))[encoding_key] || :unable_to_fetch_encoding_key) do
{:error, _} = e -> e
k -> {:ok, k}
end
end
defp firebase_jwk(encoding_key) do
{:ok, google_cert} = fetch_firebase_key(encoding_key)
[cert] = :public_key.pem_decode(google_cert)
{:Certificate, {:TBSCertificate, _, _, _, _, _, _, {:SubjectPublicKeyInfo,
{:AlgorithmIdentifier, _, _}, rsa_pub_key_der}, _, _, _}, _, _} = :public_key.pem_entry_decode(cert)
rsa_pub_key = :public_key.der_decode(:RSAPublicKey, rsa_pub_key_der)
JOSE.JWK.from_key(rsa_pub_key)
end
defp firebase_secret(token) do
[header|_t] = String.split(token, ".")
jwk = :base64url.decode(header)
|> Poison.decode!()
|> Map.get("kid")
|> firebase_jwk()
end
#-----------------------------------------------------------------------------
# Below identicial to Guardian.Plug.VerifyHeader
# with small tweak to pass firebase_secret to Guardian.decode_and_verify
#-----------------------------------------------------------------------------
def init(opts \\ %{}) do
opts_map = Enum.into(opts, %{})
realm = Map.get(opts_map, :realm)
if realm do
{:ok, reg} = Regex.compile("#{realm}\:?\s+(.*)$", "i")
opts_map = Map.put(opts_map, :realm_reg, reg)
end
opts_map
end
def call(conn, opts) do
key = Map.get(opts, :key, :default)
case Guardian.Plug.claims(conn, key) do
{:ok, _} -> conn
{:error, :no_session} ->
verify_token(conn, fetch_token(conn, opts), key)
_ -> conn
end
end
defp verify_token(conn, nil, _), do: conn
defp verify_token(conn, "", _), do: conn
defp verify_token(conn, token, key) do
case Guardian.decode_and_verify(token, %{"secret" => firebase_secret(token)}) do
{:ok, claims} ->
conn
|> Guardian.Plug.set_claims({:ok, claims}, key)
|> Guardian.Plug.set_current_token(token, key)
{:error, reason} ->
Guardian.Plug.set_claims(conn,{:error, reason}, key)
end
end
defp fetch_token(conn, opts) do
fetch_token(conn, opts, Plug.Conn.get_req_header(conn, "authorization"))
end
defp fetch_token(_, _, nil), do: nil
defp fetch_token(_, _, []), do: nil
defp fetch_token(conn, opts = %{realm_reg: reg}, [token|tail]) do
trimmed_token = String.strip(token)
case Regex.run(reg, trimmed_token) do
[_, match] -> String.strip(match)
_ -> fetch_token(conn, opts, tail)
end
end
defp fetch_token(_, _, [token|_tail]), do: String.strip(token)
end
from erlang-jose.
Related Issues (20)
- This project is turning into abandonware: call for more maintainers HOT 4
- Actually run Elixir tests in CI
- Speed up CI, currently takes ~20 minutes to run
- Update ECDH-1PU related code to match latest draft
- Add support for JWK Thumbprint URI from IETF RFC 9278
- Add support for ECDH-SS JWE algorithms HOT 1
- Add support for ES256K algorithm
- More robust support detection mechanism
- jwk.ex: Reading from pem file fails with FunctionClauseError
- Support AWS ALB JWTs with padding
- How to include headers after compact/1? HOT 1
- CaseClauseError raised by JOSE.JWT.peek_protected/1 with malformed token
- CVE-2023-50966: DoS via a large p2c value in a JOSE header HOT 3
- Support OTP JSON Implementation
- Problem compiling Jose 1.11.8 with Rebar3 HOT 2
- Upgrade error for v1.11.8 HOT 1
- Spec for verify_strict/3 missing {class, reason} results from try/catch HOT 1
- Dialyzer is broken in version 1.11.10
- `public_key` deprecations in OTP `27.0` HOT 6
- CVE-2023-50966 has no fix version HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from erlang-jose.