Reddit api oauth 认证长生不老药

Reddit api oauth authentication elixir

我正在尝试检索访问令牌。我已经设法让用户授权我的应用程序,现在我正在尝试检索访问令牌。 这是 reddit oauth2 文档:https://github.com/reddit-archive/reddit/wiki/oauth2 这是我正在使用的 HTTPoison post 请求:https://hexdocs.pm/httpoison/HTTPoison.html#post/4

我不知道如何提出 post 请求,client_id 应该在 body 还是在 header 等等

  def get_oauth_token(token, state) do
    # TODO: compare state with old state to prevent malicious users
    cfg = config()

    url = 'https://www.reddit.com/api/v1/access_token'
    body  = %{
      grant_type: "authorization_code",
      code: token,
      redirect_uri: cfg[:redirect_uri],
      client_id: cfg[:client_id],
      client_secret: cfg[:client_secret]
    }
    |> Jason.encode()
    |> ok()

    HTTPoison.post(url, body, [
      {"Accept", "application/json"},
      {"Content-Type", "application/x-www-form-urlencoded"},
    ])
  end

  defp ok({:ok, response}), do: response

我收到状态码 401

预期结果

{
    "access_token": Your access token,
    "token_type": "bearer",
    "expires_in": Unix Epoch Seconds,
    "scope": A scope string,
    "refresh_token": Your refresh token
}

API 期望 application/x-www-form-urlencoded,因此您不应编码为 JSON。

根据 Reddit docs,您还需要使用 HTTP 基本身份验证将 client_idclient_secret 编码为 Authorization header。

url = "https://www.reddit.com/api/v1/access_token"

headers = [
  {"Content-Type", "application/x-www-form-urlencoded"},
  {"Authorization", "Basic " <> Base.encode64("#{cfg.client_id}:#{cfg.client_secret}")}
]

data = [
  grant_type: "authorization_code",
  code: token,
  redirect_uri: cfg.redirect_uri
]

HTTPoison.post(url, {:form, data}, headers)

查看 HTTPoison.Request 的文档,了解发布表单 {:form, data} 语法 url-encoded。