Rails app使用googleAPI作为登录错误

时间:2017-11-28 21:36:41

标签: ruby-on-rails google-api

我正在逐步完成本文:https://richonrails.com/articles/google-authentication-in-ruby-on-rails/ 我创建了一个全新的rails应用程序以进行测试。 但我一直得到同样的错误:错误:invalid_request

redirect_uri的参数值无效:不允许使用原始IP地址:http://0.0.0.0:3000/auth/google_oauth2/callback  OmniAuth.config.logger = Rails.logger

omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, 'CLIENT-ID', 'SECRET', {client_options: {ssl:
    {ca_file: Rails.root.join("cacert.pem").to_s}}}
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

user.rb

class User < ApplicationRecord
  def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.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

ApplicationController.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

SessionController.rb     class SessionsController&lt; ApplicationController的       def创建          user = User.from_omniauth(env [“omniauth.auth”])          session [:user_id] = user.id          redirect_to root_path       端

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

请帮帮我!非常感谢!

2 个答案:

答案 0 :(得分:1)

在您的google dev API信息中心内,您必须将回调网址更改为http://localhost:3000/auth/google_oauth2/callback以外的其他内容

开发环境中的解决方法是将回调网址更改为[TestClass] public class BaseTestClass { [TestInitialize] public virtual void Setup() { } }

Google API Callback URL

答案 1 :(得分:1)

Andy's answer仅在您编辑系统的/ etc / hosts文件时将0.0.0.0重定向到以.com或.net等非原始地址结尾的网址才有效,具体是错误“消息不允许原始IP地址”是指。如果您同时执行这两项操作,那么您的应用应该适用于您的开发环境。

要执行此操作,请使用首选文本编辑器打开/ etc / hosts。由于这是受保护的系统文件,因此您需要处于管理员模式。例如:$ sudo vi /etc/hosts

将该行添加到文件的底部:

0.0.0.0  my-custom-domain.com

重新启动shell会话和开发服务器,以使更改生效。

需要授权自定义重定向网址(“my-custom-domain.com”)。返回Google Dev API信息中心,将http://my-custom-domain.com:3000/auth/google_oauth2/callback添加到您的授权重定向URI。

相关问题