{"id":19645817,"url":"https://github.com/approov/quickstart-elixir-phoenix-guardian-token-check","last_synced_at":"2025-07-03T09:06:23.273Z","repository":{"id":54728370,"uuid":"302615082","full_name":"approov/quickstart-elixir-phoenix-guardian-token-check","owner":"approov","description":"Approov integration example for the Elixir Phoenix framework with the Guardian library for JWT token checks.","archived":false,"fork":false,"pushed_at":"2022-12-20T18:41:23.000Z","size":51,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-06-04T13:46:40.486Z","etag":null,"topics":["api","approov","approov-integration","approov-quickstart","elixir","elixir-lang","elixir-phoenix","elixir-phoenix-framework","elixir-phoenix-guardian","guardian-library","jwt","jwt-token","phoenix-framework"],"latest_commit_sha":null,"homepage":"","language":"Elixir","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/approov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-10-09T10:59:58.000Z","updated_at":"2022-11-03T07:51:51.000Z","dependencies_parsed_at":"2023-01-30T01:31:23.762Z","dependency_job_id":null,"html_url":"https://github.com/approov/quickstart-elixir-phoenix-guardian-token-check","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/approov/quickstart-elixir-phoenix-guardian-token-check","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-elixir-phoenix-guardian-token-check","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-elixir-phoenix-guardian-token-check/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-elixir-phoenix-guardian-token-check/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-elixir-phoenix-guardian-token-check/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/approov","download_url":"https://codeload.github.com/approov/quickstart-elixir-phoenix-guardian-token-check/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-elixir-phoenix-guardian-token-check/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263296443,"owners_count":23444489,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","approov","approov-integration","approov-quickstart","elixir","elixir-lang","elixir-phoenix","elixir-phoenix-framework","elixir-phoenix-guardian","guardian-library","jwt","jwt-token","phoenix-framework"],"created_at":"2024-11-11T14:35:28.639Z","updated_at":"2025-07-03T09:06:23.240Z","avatar_url":"https://github.com/approov.png","language":"Elixir","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Approov QuickStart - Elixir Phoenix Guardian Token Check\n\n[Approov](https://approov.io) is an API security solution used to verify that requests received by your backend services originate from trusted versions of your mobile apps.\n\nThis repo implements the Approov server-side request verification code in [Elixir](https://elixir-lang.org/), which performs the verification check before allowing valid traffic to be processed by the API endpoint.\n\nThis is an Approov integration quickstart example for the Elixir Phoenix framework, that uses the Guardian library to check the Approov token. If you are looking for another Elixir integration you can check our list of [quickstarts](https://approov.io/docs/latest/approov-integration-examples/backend-api/), and if you don't find what you are looking for, then please let us know [here](https://approov.io/contact).\n\n\n\n## Approov Integration Quickstart\n\nThe quickstart was tested with the following Operating Systems:\n\n* Ubuntu 20.04\n* MacOS Big Sur\n* Windows 10 WSL2 - Ubuntu 20.04\n\nFirst, setup the [Approov CLI](https://approov.io/docs/latest/approov-installation/index.html#initializing-the-approov-cli).\n\nNow, register the API domain for which Approov will issues tokens:\n\n```bash\napproov api -add api.example.com\n```\n\n\u003e **NOTE:** By default a symmetric key (HS256) is used to sign the Approov token on a valid attestation of the mobile app for each API domain it's added with the Approov CLI, so that all APIs will share the same secret and the backend needs to take care to keep this secret secure.\n\u003e\n\u003e A more secure alternative is to use asymmetric keys (RS256 or others) that allows for a different keyset to be used on each API domain and for the Approov token to be verified with a public key that can only verify, but not sign, Approov tokens.\n\u003e\n\u003e To implement the asymmetric key you need to change from using the symmetric HS256 algorithm to an asymmetric algorithm, for example RS256, that requires you to first [add a new key](https://approov.io/docs/latest/approov-usage-documentation/#adding-a-new-key), and then specify it when [adding each API domain](https://approov.io/docs/latest/approov-usage-documentation/#keyset-key-api-addition). Please visit [Managing Key Sets](https://approov.io/docs/latest/approov-usage-documentation/#managing-key-sets) on the Approov documentation for more details.\n\nNext, enable your Approov `admin` role with:\n\n```bash\neval `approov role admin`\n````\n\nFor the Windows powershell:\n\n```bash\nset APPROOV_ROLE=admin:___YOUR_APPROOV_ACCOUNT_NAME_HERE___\n````\n\nNow, retrieve the [Approov secret](https://approov.io/docs/latest/approov-usage-documentation/#account-secret-key-export):\n\n```bash\napproov secret -get base64Url\n```\n\nNext, export the Approov secret into the environment:\n\n```bash\nexport APPROOV_BASE64URL_SECRET=approov_base64url_secret_here\n```\n\nNow, you need to retrieve the Approov secret from your running application. From Elixir `1.11` we have the runtime configuration, that will run every-time a release or a Mix project is started, thus the ideal place to retrieve the Aproov secret from the environment. Add the following code to your `config/runtime.exs`:\n\n```elixir\napproov_secret =\n  System.get_env(\"APPROOV_BASE64_SECRET\") ||\n    raise \"Environment variable APPROOV_BASE64_SECRET is missing.\"\n\nconfig :YOUR_APP, YOUR_APP.ApproovTokenPlug,\n  allowed_algos: [\"HS256\"],\n  secret_key: Base.decode64!(approov_secret)\n```\n\n\u003e **NOTE:** If you are below Elixir `1.11` then follow [this quickstart](/docs/APPROOV_TOKEN_QUICKSTART.md#approov-secret) steps to add the Approov secret to your application.\n\nNext, to check the Approov token you need to add the [ueberauth/guardian](https://github.com/ueberauth/guardian) package to your dependencies on `mix.exs`:\n\n```elixir\n{:guardian, \"~\u003e 2.0\"}\n```\n\nNow, you can install it with:\n\n```\nmix install\n```\n\nNext, add the [Approov Token Plug](/src/approov-protected-server/token-check/hello/lib/hello_web/plugs/approov_token_plug.ex) module to your project at `lib/your_app_web/plugs/approov_token_plug.ex`:\n\n```elixir\ndefmodule YOUR_APP.ApproovTokenPlug do\n  require Logger\n\n  ##############################################################################\n  # Adhere to the Phoenix Module Plugs specification by implementing:\n  #   * init/1\n  #   * call/2\n  #\n  # @link https://hexdocs.pm/phoenix/plug.html#module-plugs\n  ##############################################################################\n\n  def init(options), do: options\n\n  def call(conn, _options) do\n    with {:ok, conn, _approov_token_claims} \u003c- _verify_approov_token(conn) do\n      conn\n    else\n      {:error, conn} -\u003e\n        conn |\u003e _halt_connection()\n    end\n  end\n\n  ##############################################################################\n  # Inject Guardian functions and implement the required behaviour callbacks:\n  #   * subject_for_token/2\n  #   * resource_from_claims/2\n  #\n  # The required behaviour functions are not necessary in the context of\n  # checking the Approov token, but required to be implemented in order to use\n  # Guardian.\n  ##############################################################################\n\n  use Guardian, otp_app: :hello\n\n  @impl true\n  def subject_for_token(user, _claims), do: {:ok, to_string(user.id)}\n\n  @impl true\n  def resource_from_claims(claims), do: {:ok, claims[\"sub\"]}\n\n  defp _verify_approov_token(conn) do\n    with [approov_token | _] \u003c- Plug.Conn.get_req_header(conn, \"approov-token\"),\n         {:ok, approov_token_claims} \u003c- decode_and_verify(approov_token),\n         :ok \u003c- _verify_expiration(approov_token_claims) do\n      {:ok, conn, approov_token_claims}\n    else\n      [] -\u003e\n        # You may want to add some logging here\n        {:error, conn}\n\n      {:error, reason} when is_atom(reason) -\u003e\n        # You may want to add some logging here\n        {:error, conn}\n\n      {:error, %ArgumentError{} = error} -\u003e\n        # You may want to add some logging here\n        {:error, conn}\n\n      {:error, error} -\u003e\n        # You may want to add some logging here\n        {:error, conn}\n    end\n  end\n\n  defp _verify_expiration(%{\"exp\" =\u003e timestamp}) do\n    datetime = _timestamp_to_datetime(timestamp)\n    now = DateTime.utc_now()\n\n    case DateTime.compare(now, datetime) do\n      :lt -\u003e\n        :ok\n\n      _ -\u003e\n        {:error, :approov_token_expired}\n    end\n  end\n\n  defp _verify_expiration(_claims) do\n    {:error, :missing_exp_claim}\n  end\n\n  defp _timestamp_to_datetime(timestamp) when is_integer(timestamp) do\n    DateTime.from_unix!(timestamp)\n  end\n\n  defp _timestamp_to_datetime(timestamp) when is_float(timestamp) do\n    {timestamp, _decimals} = Integer.parse(\"#{timestamp}\")\n    DateTime.from_unix!(timestamp)\n  end\n\n  defp _halt_connection(conn) do\n    conn\n    |\u003e Plug.Conn.put_status(401)\n    |\u003e Phoenix.Controller.json(%{})\n    |\u003e Plug.Conn.halt()\n  end\nend\n```\n\n\u003e **NOTE:** When the Approov token validation fails we return a `401` with an empty body, because we don't want to give clues to an attacker about the reason the request failed, and you can go even further by returning a `400`.\n\nNow, add the [Approov Token Plug](/src/approov-protected-server/token-check/hello/lib/hello_web/plugs/approov_token_plug.ex) to the `:api` pipeline on your Phoenix router `lib/your_app_web/router.ex`:\n\n```elixir\npipeline :api do\n  plug :accepts, [\"json\"]\n\n  # Ideally you will not want to add any other Plug before the Approov Token\n  # check to protect your server from wasting resources in processing requests\n  # not having a valid Approov token. This increases availability for your\n  # users during peak time or in the event of a DoS attack(We all know the\n  # BEAM design allows to cope very well with this scenarios, but best to play\n  # in the safe side).\n  plug YourAppWeb.ApproovTokenPlug\nend\n```\n\nNot enough details in the bare bones quickstart? No worries, check the [detailed quickstarts](QUICKSTARTS.md) that contain a more comprehensive set of instructions, including how to test the Approov integration.\n\n\n## More Information\n\n* [Approov Overview](OVERVIEW.md)\n* [Detailed Quickstarts](QUICKSTARTS.md)\n* [Step by Step Examples](EXAMPLES.md)\n* [Testing](TESTING.md)\n\n### System Clock\n\nIn order to correctly check for the expiration times of the Approov tokens is very important that the backend server is synchronizing automatically the system clock over the network with an authoritative time source. In Linux this is usually done with a NTP server.\n\n\n## Issues\n\nIf you find any issue while following our instructions then just report it [here](https://github.com/approov/quickstart-elixir-phoenix-guardian-token-check/issues), with the steps to reproduce it, and we will sort it out and/or guide you to the correct path.\n\n\n## Useful Links\n\nIf you wish to explore the Approov solution in more depth, then why not try one of the following links as a jumping off point:\n\n* [Approov Free Trial](https://approov.io/signup)(no credit card needed)\n* [Approov Get Started](https://approov.io/product/demo)\n* [Approov QuickStarts](https://approov.io/docs/latest/approov-integration-examples/)\n* [Approov Docs](https://approov.io/docs)\n* [Approov Blog](https://approov.io/blog/)\n* [Approov Resources](https://approov.io/resource/)\n* [Approov Customer Stories](https://approov.io/customer)\n* [Approov Support](https://approov.io/contact)\n* [About Us](https://approov.io/company)\n* [Contact Us](https://approov.io/contact)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapproov%2Fquickstart-elixir-phoenix-guardian-token-check","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fapproov%2Fquickstart-elixir-phoenix-guardian-token-check","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapproov%2Fquickstart-elixir-phoenix-guardian-token-check/lists"}