Skip to content

Instantly share code, notes, and snippets.

@jchoca
Last active January 19, 2020 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchoca/29d8ea2a3bf2cd36cd15d9eb45835659 to your computer and use it in GitHub Desktop.
Save jchoca/29d8ea2a3bf2cd36cd15d9eb45835659 to your computer and use it in GitHub Desktop.
Making a request to the GitHub app API in Elixir

Add the jerl Erlang library in mix.exs file

{:jwerl, "~> 1.1"}
defmodule GithubJwt do
  def github_api_test do
    jwt = create_jwt("/path/to/pemfile", APP_ID)
    test_token(jwt)
  end

  defp test_token(jwt) do
    Application.ensure_all_started(:inets)
    Application.ensure_all_started(:ssl)

    auth_header_val = to_charlist("Bearer #{jwt}")
    request =
      {'https://api.github.com/app',
       [
         {'Authorization', auth_header_val},
         {'Accept', 'application/vnd.github.machine-man-preview+json'},
         {'User-Agent', 'ElixirTestApp/1.0.0'}
       ]}

    :httpc.request(:get, request, [], [])
  end

  defp create_jwt(filepath, app_id, exp_time_min \\ 10) do
    {:ok, private_pem} = File.read(filepath)
    now = DateTime.to_unix(DateTime.utc_now())
    exp_time = now + exp_time_min * 60
    Jwerl.sign([iat: now, exp: exp_time, iss: app_id], :rs256, private_pem)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment