【问题标题】:Instagram API returns a code, but when requesting an access token says the same code is invalidInstagram API 返回一个代码,但在请求访问令牌时说相同的代码无效
【发布时间】:2015-02-11 00:39:17
【问题描述】:

使用 Instagram ruby​​gem 和 sinatra,我能够从一个小型 AngularJS 应用程序通过 oauth 成功进行身份验证,并使用 Instagram API。以下是我的 sinatra 应用程序中的相关 oauth 路由:

get '/oauth/connect' do
    logger.info "going here " + (Instagram.authorize_url :redirect_uri => CALLBACK)
    redirect Instagram.authorize_url :redirect_uri => CALLBACK
end

get "/oauth/callback" do
    logger.info params[:code]
    response = Instagram.get_access_token params[:code], :redirect_uri => CALLBACK
    session[:access_token] = response.access_token

    users = DB[:users]
    current_user = users[:instagram_id => response.user.id.to_i]

    if current_user.nil?
        new_user = response.user
        users.insert :instagram_id => new_user.id.to_i, 
                             :username => new_user.username, 
                             :profile_picture => new_user.profile_picture,
                             :created_at => DateTime.now

        current_user = users[:instagram_id => new_user.id]
    end
    session[:current_user] = current_user
    redirect "/app"
end

但是,当尝试使用相同的路由(GET oauth/connect,重定向到 Instagram,然后重定向回 oauth/callback)从 Android 应用程序的 webview 中进行身份验证时,我收到以下错误:

Instagram::BadRequest - POST https://api.instagram.com/oauth/access_token/: 400: OAuthException: No matching code found.:

我已确认我使用的是从 Instagram 返回的相同代码,并且 redirect_uri 与我在 Instagram 注册的相同。

注意,Oauth 在我使用网络界面时有效,但不是通过 Android 网络视图。

我阅读了许多其他人看到此行为的帖子,但提供的解决方案对我不起作用:

  1. Instagram 可以禁用您的应用,因为它认为它行为不端。不,因为 oauth 通过我的网络界面工作,仍然使用相同的客户端 ID 和密钥以及相同的路由。

  2. 您使用的 redirect_uri 与 Instagram 中列出的不同。我已经检查并重新检查了它,它看起来很好。

接下来我可以在哪里调试以了解此问题的根源?

【问题讨论】:

    标签: android ruby oauth instagram


    【解决方案1】:

    我知道我的答案有点晚了,但我将其发布在这里,以便其他人(希望)不必像我一样努力搜索。

    您似乎正在使用显式身份验证。我们使用显式流程遇到了这个问题。

    问题在于:在您将代码发送到 Instagram(第 3 步)后,该代码立即失效。但是,Instagram 不会在至少 5 分钟内向您发送新代码(步骤 1 和 2)(它会重新发布旧代码)。

    确保您不会使用相同的代码发送多个请求(Android WebView 倾向于任意发送多个请求)。或者,更好的是,在服务器上缓存 code->Instagram_response 映射。

    【讨论】:

    • 是的,Android WebView onPageFinished 回调触发了两次,我正在启动两个身份验证调用。
    • @user2028,抱歉,我已经快 5 年没有接触过 Instagram API了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多