Reddit API OAuth身份验证灵丹妙药 [英] Reddit api oauth authentication elixir

查看:29
本文介绍了Reddit API OAuth身份验证灵丹妙药的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索访问令牌。我已经设法让用户授权我的应用程序,现在我正在尝试检索访问令牌。 下面是reddit OAuth2文档:https://github.com/reddit-archive/reddit/wiki/oauth2 下面是我正在使用的HTTPoison POST请求: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
}

推荐答案

API需要application/x-www-form-urlencoded,所以您不应该编码为JSON。

根据Reddit docs,您还需要使用HTTP基本身份验证将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)

有关URL编码的发布表单的{:form, data}语法,请查看HTTPoison.Request的文档。

这篇关于Reddit API OAuth身份验证灵丹妙药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆