简体   繁体   中英

Omniauth isn't catching the initial get “/auth/:provider” request

Followed the setup documentation verbatim

In the gemfile

gem 'omniauth'
gem 'omniauthgithub'
gem 'dotenv-rails'

In config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, ENV['GITHUB_CLIENT_ID'], ENV['GITHUB_CLIENT_SECRET']
end

And the link for the user

<%= link_to "Log in with GitHub!", "/auth/github" %>

The call back route is set as well

get '/auth/:provider/callback' => 'sessions#create'

But it doesn't get that far. When I click on the link there is an immediate routing error

No route matches [GET] "/auth/github"

Everything I can find indicates the initial "/auth/:provider" request is intercepted with the Omniauth black-box magic and that all I should have to do is configure the callback route. I've tried this entire setup with Facebook as well just to see if it was something Github specific but no luck. I've wiped the Gemfile.lock and re-ran bundle install just to make sure the gems are all in working order but that didn't change anything. All the other omniauth issues I've found articles about were regarding the callback routing, not the initial get request- which leads me to believe it's either something extremely obvious or very obscure. Please Help!

As @obiruby said, this is due to the new CSRF protection enabled by default in OmniAuth 2.0+.

If you are using GitHub as your sole method of authentication, the CSRF isn't a threat, so you can safely re-enable the GET method by adding the following line to config/initializers/omniauth.rb:

OmniAuth.config.allowed_request_methods = [:get, :post]

I've been struggling with the exact same issue today (except I'm integrating google_oauth2 not github), and what finally worked for me included following the recently updated instructions from the Devise wiki .

Specifically, the part about making sure to use POST requests:

OmniAuth 2.0+ requires using HTTP POST as the request method to initiate the authentication, so your link should be configured with method: :post: (this requires rails-ujs or similar to create POST requests)

So once I changed my view to use button_to instead of link_to (alternatively I could have used link_to with method: :post ) I had gotten it to work.

Also, are you using Devise as well? If so, make sure to follow the devise-related setup instructions (specifically, to delete config/intializers/omniauth.rb and instead to put your setup credentials in config/initializers/devise.rb as indicatd in the aforementioned wiki post... otherwise it apparently conflicts in a very silent way which can make for a "very fun" debug sesh)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM