我有一个 Rails 应用程序和一个 Wordpress 网站。 Rails 数据库中的所有用户。现在我想提供从Rails 应用程序到wordpress 的SSO。
我发现了一些东西,但大多数都提供从 Wordpress 到 Rails 的 SSO。
你有什么想法来解决这个任务吗?
谢谢。
最佳答案
你的问题有点含糊,所以我会尽力而为。
首先您应该将 devise/omniauth gem 添加到 Gemfile
gem 'devise'
gem 'omniauth'
gem 'omniauth-wordpress-oauth2-plugin', github: 'jwickard/omniauth-wordpress-oauth2-plugin'
为您的 WordPress 站点安装 Oauth2 提供程序插件:
https://github.com/jwickard/wordpress-oauth
为您的 Rails 应用创建客户端条目,并将回调键设置为: http://example.com/users/auth/wordpress_oauth2/callback
然后你必须配置 Devise/Omniauth
#config/initializers/devise.rb
config.omniauth :wordpress_oauth2, ENV['APP_ID'], ENV['APP_SECRET'],
strategy_class: OmniAuth::Strategies::WordpressOauth2Plugin,
client_options: { 站点: ' http://yourcustomwordpress.com ' }
现在您必须设置路由以允许回调
#config/routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }
创建回调 Controller
#app/controllers/omniauth_callbacks_controller.rb
class OmniauthCallbacksController < ApplicationController
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
现在您必须确保用户模型是可全方位验证的
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
...
def self.find_for_wordpress_oauth2(oauth, signed_in_user=nil)
#if the user was already signed in / but they navigated through the authorization with wordpress
if signed_in_user
#update / synch any information you want from the authentication service.
if signed_in_user.email.nil? or signed_in_user.email.empty?
signed_in_user.update_attributes(email: oauth['info']['email'])
end
return signed_in_user
else
#find user by id and provider.
user = User.find_by_provider_and_uid(oauth['provider'], oauth['uid'])
#if user isn't in our database yet, create it!
if user.nil?
user = User.create!(email: oauth['info']['email'], uid: oauth['uid'], provider: oauth['provider'],
nickname: oauth['extra']['user_login'], website: oauth['info']['urls']['Website'],
display_name: oauth['extra']['display_name'])
end
user
end
end
end
希望这能够帮助到您
关于ruby-on-rails-4 - 从 Rails 登录 WordPress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36512633/