Giter VIP home page Giter VIP logo

omniauth-wordpress-oauth2-plugin's Introduction

Omniauth::Wordpress

A Wordpress Oauth2 Provider Plugin Strategy for Omniauth

Use with the Wordpress Oauth2 Provider plugin to turn your wordpress install into an authentication provider: https://github.com/jwickard/wordpress-oauth

Installation

Add this line to your application's Gemfile:

gem 'omniauth-wordpress_hosted', github: 'jwickard/omniauth-wordpress-oauth2-plugin'

And then execute:

$ bundle

Usage

Devise / Omniauth

Add provider to your config/initializers/devise.rb ex:

config.omniauth :wordpress_hosted, 'APP_KEY', 'APP_SECRET',
                  strategy_class: OmniAuth::Strategies::WordpressHosted, 
                  client_options: { site: 'http://yourcustomwordpress.com' }

Omniauth / Rails

Add provider to your config/initializers/omniauth.rb ex:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :wordpress_hosted, 'APP_KEY', 'APP_SECRET',
                  strategy_class: OmniAuth::Strategies::WordpressHosted, 
                  client_options: { site: 'http://yourcustomwordpress.com' }
end

Add Provider to Wordpress

Asuming you have already installed the wordpress oauth2 provider plugin, add a provider for this rails applicaiton to the plugin configuration:

alt tag

make sure the callback url you have configured is of the form:

http://your-rails-site.com/users/auth/wordpress_hosted/callback

Then configure your rails application with the app key and secret generated by the wordpress plugin.

Add callback

Configure routes to add omniauth callbacks controller config/routes.rb (which you implement):

devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }

Implement omniauth_callbacks controller app/controllers/omniauth_callbacks_controller.rb :

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def wordpress_hosted
    #You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.find_for_wordpress_hosted(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Wordpress Oauth2"
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
    else
      session["devise.wordpress_hosted"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

Example Oauth Data

--- !ruby/hash:OmniAuth::AuthHash
provider: wordpress_hosted
uid: '2'
info: !ruby/hash:OmniAuth::AuthHash::InfoHash
  name: Joe Sandstone
  email: [email protected]
  nickname: jsand
  urls: !ruby/hash:OmniAuth::AuthHash
    Website: http://example.com
credentials: !ruby/hash:OmniAuth::AuthHash
  token: 4070b5be481b1a4110797763ac27359c1d1da3bb
  refresh_token: 212597ee673d630cfb95a77a69900c7ead1d3e19
  expires_at: 1387912450
  expires: true
extra: !ruby/hash:OmniAuth::AuthHash
  ID: '2'
  user_login: jsand
  user_nicename: jsand
  user_email: [email protected]
  user_url: http://example.com
  user_registered: '2013-12-12 15:29:34'
  user_status: '0'
  display_name: Joe Sandstone

Example application

https://github.com/jwickard/omniauth-wordpress-oauth2-plugin-example

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

License

Copyright (c) 2013 Joel Wickard

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

omniauth-wordpress-oauth2-plugin's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

omniauth-wordpress-oauth2-plugin's Issues

Intermittent login failures

I have been using this for a while with great success to allow single sign on between a rails app my wordpress site. The rails app is 4.1.6 on ruby version 2.1.3p242

Lately I've been experiencing intermittent login failures when authenticating via my wordpress site. This occurs on both my live app and when testing via my local test instance.

It happens regardless of being logged into wordpress or not. If not logged into wordpress I'm prompted for my password and then it fails, otherwise it fails after trying to connect.

When I look at the logs I see the following error

Started GET "/users/auth/wordpress_hosted/callback?code=00dd73317a8fdc9c4a9acdd8fdbdb7fc2c53ce02&state=f0d26dd2d85ce217b9b304a05cfc839fc2cdb9ce253c3e21" for 127.0.0.1 at 2015-06-12 16:47:34 -0700
I, [2015-06-12T16:47:34.885836 #9774]  INFO -- omniauth: (wordpress_hosted) Callback phase initiated.
E, [2015-06-12T16:47:36.261085 #9774] ERROR -- omniauth: (wordpress_hosted) Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: The authorization code has expired
{"error":"invalid_grant","error_description":"The authorization code has expired"}
Processing by OmniauthCallbacksController#failure as HTML
  Parameters: {"code"=>"00dd73317a8fdc9c4a9acdd8fdbdb7fc2c53ce02", "state"=>"f0d26dd2d85ce217b9b304a05cfc839fc2cdb9ce253c3e21"}
Redirected to http://localhost:3000/users/sign_in
Completed 302 Found in 1ms (ActiveRecord: 0.0ms)

Upon failure I'm forwarded back to login screen and the message that is returned from wordpress blames bad credentials despite the fact that they were correct or that the user was already signed into the wordpress site.

Another thing to note about the log is that I see two entries about the request phase being initiated back to back. Is this expected behavior and it could be the cause for my intermittent login failures?

Started GET "/users/auth/wordpress_hosted" for 127.0.0.1 at 2015-06-12 16:47:31 -0700
I, [2015-06-12T16:47:31.310787 #9774]  INFO -- omniauth: (wordpress_hosted) Request phase initiated.
Started GET "/users/auth/wordpress_hosted" for 127.0.0.1 at 2015-06-12 16:47:31 -0700
I, [2015-06-12T16:47:31.328794 #9774]  INFO -- omniauth: (wordpress_hosted) Request phase initiated.

Redirect after login not working

I'm trying this gem on rails 5.2 and ruby 2.4

Here is my gemfile

gem 'omniauth'
gem 'omniauth-oauth2', '1.3.1' # DO NOT change this! If we update teo 1.4 the SSO doesnt work anymore
gem 'omniauth-wordpress_hosted', github: 'jwickard/omniauth-wordpress-oauth2-plugin'

Everything seems to work fine up to the moment after the login.
Then i get the message bellow

Started GET "/users/auth/wordpress_hosted/callback?state=3e1713c400efca580533b59100907731ccfef150d3e48cdf&code=[FILTERED]" for 127.0.0.1 at 2018-06-15 11:52:33 -0700
I, [2018-06-15T11:52:33.002608 #783]  INFO -- omniauth: (wordpress_hosted) Callback phase initiated.
E, [2018-06-15T11:52:33.012354 #783] ERROR -- omniauth: (wordpress_hosted) Authentication failure! invalid_credentials: OAuth2::Error, <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /oauth/token was not found on this server.</p>
</body></html>

Processing by OmniauthCallbacksController#failure as HTML
  Parameters: {"state"=>"3e1713c400efca580533b59100907731ccfef150d3e48cdf", "code"=>"[FILTERED]"}
Redirected to http://localhost:3000/users/sign_in
Completed 302 Found in 6ms (ActiveRecord: 0.0ms)

Unable to use plugin without devise

Hey Joel, I've been trying to use your plugin without having to introduce devise as a dependency (my app is older and uses its own custom auth solution already). I'm having some trouble. I loaded your plugin the way you demonstrate for pure Rails / Omniauth integration:

Add provider to your config/initializers/omniauth.rb ex:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :wordpress_oauth2_plugin, 'APP_KEY', 'APP_SECRET',
                  strategy_class: OmniAuth::Strategies::WordpressOauth2Plugin, 
                  client_options: { site: 'http://yourcustomwordpress.com' }
end

When I get down to the "Add callback" section, you demonstrate using the #devise_for method in my routes file to add the auth and callback routes. I'm not using devise so I added these routes instead:

match "/users/auth/:provider(.:format)", controller: "omniauth_callbacks", action: "passthru", as: "user_omniauth_authorize", via: [:get, :post], constraints: { provider: /wordpress_oauth2/ }
  match "/users/auth/:action/callback(.:format)", controller: "omniauth_callbacks", action: "(?-mix:wordpress_oauth2)", as: "user_omniauth_callback", via: [:get, :post]

However, when I try to visit /users/auth/wordpress_oauth2 to start the auth process, I get this error:

Unknown action
The action 'passthru' could not be found for OmniauthCallbacksController

So it seems devise is providing a #passthru action that has to be in place in order for this to work properly. I assume I can write my own #passthru action but I'm not sure what needs to be there. Do you have any further guidance on how to get your plugin working without having devise as a dependency?

Not found. Authentication passthru.

I'm attempting to use the omniauth-wordpress_hosted gem to sign into a WordPress site, but I keep getting an error:

"Not found. Authentication passthru."

Here's my gemfile:

gem 'devise'
gem 'omniauth'
gem 'omniauth-wordpress_hosted', github: 'jwickard/omniauth-wordpress-oauth2-plugin'

Here's my Omniauth Callbacks Controller:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def wordpress_oauth2
#You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_wordpress_oauth2(request.env["omniauth.auth"], current_user)

if @user.persisted?
  flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Wordpress Oauth2"
  sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
else
  session["devise.wordpress_oauth2_data"] = request.env["omniauth.auth"]
  redirect_to new_user_registration_url
end

end
end

Here's my devise.rb:

config.omniauth :wordpress_oauth2,
"63A25y8nPbM113iAfyoZQBnH2bR2Ve", "x2h74mGdJwowyqzR0OpoOfZbW1mN4i",
strategy_class: OmniAuth::Strategies::WordpressHosted,
client_options: {
site: 'http://example.exampleurl.com'
}

And lastly, my routes:

devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }

Am I missing anything? I've followed the Facebook tutorial for Omniauth and haven't seen anything glaring that I'm missing.

I'm on the latest versions of Rails and Devise, along with Ruby 2.2.2

Raw info retrieval is broken

Just grabbed the latest code that includes the changes from @neiltron that were merged into master on May 16th. It immediately broke my install and I began seeing an empty hash in response instead of the raw info I was used to getting.

I've tracked down the problem to line 35 in wordpress_hosted.rb:

@raw_info = access_token.get(access_token.options[:access_url], :params => { access_token: access_token.token } ).parsed || {}

access_token.options[:access_url] returns nil. I think what you actually want is options[:client_options][:access_url]

I also had to undo the access token being passed as a param because it was causing auth to fail with an error about "invalid credentials."

(As an aside, it makes no sense to continue assigning to @raw_info if the result isn't being memoized like it was before.)

This is what I ended up with:

access_token.get(options[:client_options][:access_url]).parsed || {}

So the merge on May 16th definitely broke things on my end. If you'd like me to submit a pull request with these changes I'd be happy to do so, but it would be great to hear from @neiltron first as to whether this was actually working for him or not.

omniauth v1.2.1
omniauth-oauth v1.1.2

How to login using this gem?

Hi there

I've followed the guide, as well as copy/pasted the user model from: https://github.com/jwickard/omniauth-wordpress-oauth2-plugin-example

But what to do now? I can't login with devise + Wordpress login credentials. Nothing happens.

My app is: http://viachat-svom.herokuapp.com/users/sign_in

I also tried to add this link, but not sure if that's the way to login with Omniauth:
http://viachat-svom.herokuapp.com/users/auth/wordpress_oauth2/callback

My questions is: How to login after completing this guide?

Thank you

  • Jonas

redirect_uri_mismatch - invalid credentials

We’ve been banging our heads against the walls on this for nearly two weeks now. We’re running Rails 4, most recent version wp-oauth (wordpress plugin client), devise, omni-auth, and omniauth-wordpress_hosted. We have a rails app, which is authenticating against a WordPress installation.

I’ve read over everything and am 1000% confident that it’s setup correctly. It’s even behaving correctly: cl.ly/2B1e3K1m0a2a

When I return to the WordPress site, I’m logged in. However the rails app just spits out the same response. The only clue is in the log: cl.ly/2O293j3a3P3o

The redirect URI seems to be setup correctly and matches. http://cl.ly/1l1a331o410q

Are you able to offer any insight? I've reached out to the plugin author and haven't had much luck in that area.

installation fails, "Source does not contain any version of 'omniauth-wordpress-oauth2-plugin'

After adding "gem 'omniauth-wordpress-oauth2-plugin', github: 'jwickard/omniauth-wordpress-oauth2-plugin'" to my Gemfile and running bundle install command i get this error message:

Updating git://github.com/jwickard/omniauth-wordpress-oauth2-plugin.git
Fetching gem metadata from https://rubygems.org/.........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Could not find gem 'omniauth-wordpress-oauth2-plugin (>= 0) x86-mingw32' in
git://github.com/jwickard/omniauth-wordpress-oauth2-plugin.git (at master).
Source does not contain any versions of 'omniauth-wordpress-oauth2-plugin (>= 0)
x86-mingw32'

invalid_credentials: Unknown request

Hi,

I'm having a bit of a nightmare getting this working, probably something fundamental I'm missing on the Rails end.

When I visit /auth/wordpress_hosted it successfully goes to WordPress and logs in, then returns to Rails, but shows this error: Could not authenticate you from WordpressHosted because "Invalid credentials".

There's a more specific error in the logs Unknown request:

Started GET "/users/auth/wordpress_hosted/callback?code=852b0819f536d44d4c6daa19a648c0c9d42fbae4&state=b79bf1b2824dd58c983263cc9e2e4bd71156b9d6e174a964"

INFO -- omniauth: (wordpress_hosted) Callback phase initiated.

ERROR -- omniauth: (wordpress_hosted) Authentication failure! invalid_credentials: OAuth2::Error, invalid_request: Unknown request

{"error":"invalid_request","error_description":"Unknown request"}

Gems:
devise 3.5.1
omniauth-wordpress_hosted 0.0.2 from git://github.com/jwickard/omniauth-wordpress-oauth2-plugin.git
oauth2 1.0.0
omniauth 1.2.2
omniauth-oauth2 1.3.1

WP:
WordPress 4.2.2
WordPress OAuth Server 3.1.3

Host:
I've tried WordPress on both Tsohost and Pantheon.

devise.rb:

  config.omniauth :wordpress_hosted, ENV['OAUTH_ID'], ENV['OAUTH_SECRET'],
                  strategy_class: OmniAuth::Strategies::WordpressHosted, 
                  client_options: { site: 'http://my-site.com' }

Have also tried putting the keys directly in here as strings.

omniauth_callbacks_controller.rb:

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def wordpress_hosted
    @user = User.find_for_wordpress_hosted(request.env["omniauth.auth"], current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Wordpress Hosted"
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
    else
      session["devise.wordpress_hosted_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

user.rb:

:omniauth_providers => [:wordpress_hosted]

..
I tried putting debug lines in and this block doesn't get executed:

 def self.find_for_wordpress_hosted(oauth, signed_in_user=nil)
    if signed_in_user
      return signed_in_user
    else
      user = User.find_by_uid(oauth['uid'])
      if user.nil?
        user = User.create!(email: oauth['info']['email'], uid: oauth['uid'], firstname: 'test', lastname: 'test')
      end
      user
    end
  end

routes.rb:

devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }

The doc says wordpress_oauth2 a few times, I ran into some prior problems with this (passthru error) but changing it to wordpress_hosted got me to the point where everything runs and I get the Unknown request error.

Should strategy_class in devise.rb be renamed to WordpressHosted in README.md?

I've been trying to implement this and have run into some problems. One of them seemed to be solved when I change the name of the strategy class in devise.rb. Your instructions still show it as:
OmniAuth::Strategies::WordpressOauth2Plugin

This resulted in the following error when running Passenger:
Message from application: uninitialized constant OmniAuth::Strategies::WordpressOauth2Plugin (NameError)

This error went away when I edited devise.rb and changed the strategy_class to:
OmniAuth::Strategies::WordpressHosted

Does that seem like the proper correction in the code? And if so, should it be updated in the README?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.