【问题标题】:Reddit api oauth authentication elixirReddit api oauth 认证长生不老药
【发布时间】:2019-11-29 05:54:40
【问题描述】:

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

我不知道如何发出 post 请求,client_id 应该在正文还是在标题等处。

  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
}

【问题讨论】:

    标签: oauth-2.0 elixir reddit httpoison


    【解决方案1】:

    API 需要 application/x-www-form-urlencoded,因此您不应将其编码为 JSON。

    根据Reddit docs,您还需要使用HTTP Basic 身份验证将client_idclient_secret 编码到Authorization 标头中。

    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 编码表单的语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多