如何解决redirect_uri_mismatch错误

时间:2015-01-19 10:55:18

标签: ruby ruby-on-rails-3 ruby-on-rails-4 google-plus

其实我正在尝试使用ROR登录Google+。当我点击登录链接时,我收到以下错误。

400. That’s an error.

Error: redirect_uri_mismatch

我在下面的部分提供我的代码片段

views\layouts\application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Google</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>
<div>
  <% if current_user %>
      Signed in as <strong><%= current_user.name %></strong>!
      <%= link_to "Sign out", signout_path, id: "sign_out" %>
  <% else %>
      <%= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in" %>
  <% end %>
</div>
<div>
  <%= yield %>
</div>
</body>
</html>

控制器\ application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  helper_method :current_user

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

控制器\ sessions_controller.rb

class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_path
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end

设置\ routes.rb中

Rails.application.routes.draw do
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

  resources :sessions, only: [:create, :destroy]
  resource :home, only: [:show]

  root to: "home#show"
end

设置\初始化\ omniauth.rb

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '641362005580-inubab5v5p5bv0596dfd9c5bh9s0kr87.apps.googleusercontent.com', 'auDnCkSEelcW6Cs7-YE7VqLR', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

模型/ user.rb

class User < ActiveRecord::Base
  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

在谷歌开发者的控制台屏幕中,我的REDIRECT URIS和javascript来源

REDIRECT URIS:http://localhost:3000/oauth2callback
 JAVASCRIPT ORIGINS :http://localhost:3000

我正在使用rails版本-4.0.2和ruby版本1.9.3。请帮我解决此错误。

1 个答案:

答案 0 :(得分:0)

我认为您可能在Google开发者控制台中重定向错误。

你可能想要:http://localhost:3000/auth/google_oauth2/callback

如果您想通过Google跟踪涵盖此OAuth流程的教程check out this one by my colleague Greg Baugues on the Twilio blog