首页 > 解决方案 > Rails Devise_token_auth invalid_credentials: OAuth2::Error

问题描述

我正在构建一个基于 restful 的 rails 5、devise_token_auth 和 Omniauth google Oauth2 的 api。

目前通过电子邮件创建的基本帐户运行良好,现在我正在尝试使用 Google 配置身份验证,但在身份验证期间我遇到了一些我无法解决的错误。

在我面临的不同错误下方:

Started GET "/omniauth/google_oauth2/callback?state=xxxxx&code=xxxxx" for 127.0.0.1 at 2018-04-24 20:57:55 +0800
I, [2018-04-24T20:57:55.496909 #14173]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
I, [2018-04-24T20:57:56.719943 #14173]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
E, [2018-04-24T20:57:57.074575 #14173] ERROR -- omniauth: (google_oauth2) Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: Code was already redeemed.
{
  "error" : "invalid_grant",
  "error_description" : "Code was already redeemed."
}
Processing by Devise::OmniauthCallbacksController#failure as HTML
  Parameters: {"state"=>"xxxxxxxx", "code"=>"xxxxxxx"}
Redirected to http://localhost:3000/auth/sign_in

或者

Started GET "/omniauth/google_oauth2/callback?state=xxxxxx&code=xxxxxx" for 127.0.0.1 at 2018-04-24 21:13:46 +0800
I, [2018-04-24T21:13:46.268484 #14173]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
I, [2018-04-24T21:13:47.609079 #14173]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
E, [2018-04-24T21:13:47.978029 #14173] ERROR -- omniauth: (google_oauth2) Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Bad Request"
}
Processing by Devise::OmniauthCallbacksController#failure as HTML
  Parameters: {"state"=>"xxxxxx", "code"=>"xxxxxx"}
Redirected to http://localhost:3000/auth/sign_in

这里还配置了:devise.rb:

  config.omniauth :google_oauth2, 
                  'xxxx.apps.googleusercontent.com',   
                  'client_secret',
                  provider_ignores_state: true,
                  :access_type => 'offline'

omn​​iauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, 
             'xxxxx.apps.googleusercontent.com',
             'client_secret',
             provider_ignores_state: true,
             :access_type => 'offline'
end

如果您对根本原因有任何想法,请随时更新它,

标签: ruby-on-railsdeviseomniauthdevise-token-authomniauth-google-oauth2

解决方案


推荐阅读