我在连接我的设计令牌Auth时遇到了麻烦,因为我从google那里得到了一个响应令牌。
我用这个包做按钮:https://www.npmjs.com/package/react-google-login
这是我想要建立的第四阶段:auth/blob/master/docs/config/multiauth.md
我从谷歌那里得到了反应按钮的回复,但是我不知道这些信息是如何被转换回来的。
这两种技术之间严重缺乏在线信息。问题的关键在于如何将这个红宝石标签转化为反应:
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>
发布于 2021-12-24 01:11:16
我知道这是旧的,但这是我的两分钱。
我用过这个宝石OmniAuth Google OAuth2。信息很清楚。在我的项目中,我使用JWT管理令牌,同时仍然存储来自Google的访问和刷新令牌。
后端
# config/initializers/devise.rb
config.omniauth :google_oauth2,
ENV['GOOGLE_CLIENT_ID'],
ENV['GOOGLE_CLIENT_SECRET'],
{ scope: "userinfo.email, userinfo.profile",
prompt: 'select_account',
image_aspect_ratio: 'square',
provider_ignores_state: true,
}
# controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
# My personal token
token = issue_token(@user)
render json: { success: true,
user: @user,
token: token,
google_token: @user.access_token,
message: "Logged in successfully." }
else
render json: { success: false,
error: @user.errors.full_messages.join("\n"),
message: 'Google sign in unsuccessful.' }
end
end
def failure
set_flash_message! :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message
render json: { success: false, message: 'Google authentication failed.', reason: failure_message, kind: OmniAuth::Utils.camelize(failed_strategy.name) }
end
private
end
# In User.rb
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
if user
user = User.update(id: user.id,
refresh_token: auth.credentials.refresh_token,
access_token: auth.credentials.token,
uid: auth.uid,
)
else
# Create a username from names, append incremental if username already exists
username ||= auth.info.first_name + auth.info.last_name
username = username.delete('^a-zA-Z0-9_').downcase
num = 1
until User.find_by(username: username).nil?
username = "#{username}#{num}"
num += 1
end
user = User.create(email: auth.info.email,
uid: auth.uid,
refresh_token: auth.credentials.refresh_token,
access_token: auth.credentials.token,
provider: auth.provider,
password: Devise.friendly_token[0, 20],
firstname: auth.info.first_name,
lastname: auth.info.last_name,
username: username,
)
end
user
end
# routes.rb
# User Routes: Devise
devise_for :users,
path_names: {
sign_in: 'login',
sign_out: 'logout',
# sign_up: 'register'
},
controllers: {
sessions: 'users/sessions',
registrations: 'users/registrations',
omniauth_callbacks: 'users/omniauth_callbacks'
}
以上路线翻译
user_google_oauth2_omniauth_authorize_path GET|POST /api/users/auth/google_oauth2(.:format)
users/omniauth_callbacks#passthru
user_google_oauth2_omniauth_callback_path GET|POST /api/users/auth/google_oauth2/callback(.:format)
users/omniauth_callbacks#google_oauth2
这里是前端
<!-- index.html -->
<head>
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
</head>
不要担心定义gapi
函数,它是在上面的script
中加载的
// RegisterContent.js
const RegisterContent = function RegisterContent() {
function handleResponse(response) {
// Save user to redux store and all the tokens to cookies
}
// callback
function signInCallback(authResult) {
if (authResult.code) {
const params = { code: authResult.code }
const path = "localhost:3000/api/users/auth/google_oauth2/callback";
// This just handdles posting with axios
postResource(path, params, handleResponse);
}
}
// This will prompt opening the google window and returns a callback upon success
const googleHandler = () => {
googleAuth.grantOfflineAccess().then(signInCallback);
};
useEffect(() => {
// Initialize the GoogleAuth object
gapi.load("auth2", function foo() {
const auth = gapi.auth2.init({
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
scope: "email profile",
});
setGoogleAuth(auth);
console.log("Init");
});
}, []);
return (
<Button onclick={googleHandler}>
Continue with Google
</Button>
);
}
提供一些资源来帮助Google登录JavaScript客户端参考、如何将Google集成到您的React应用程序中,仅此而已。
发布于 2022-10-21 13:15:27
它最终只是对那个端点的post请求,但我遇到了与您相同的问题。
您需要做的是创建这样一个表单:
<form action="<%=user_google_oauth2_omniauth_authorize_path %>" method="post">
<input type="hidden" name="authenticity_token" value="XX">
<button type="submit">Connect Google</button>
</form>
当我没有通过auth令牌或在回调控制器中添加"skip_before_action :verify_autneticity_token“时,我的测试失败了。您需要填写正确的真实性令牌,然后它工作。
通过<%= csrf_meta_tags %>
,可以将真实性令牌信息添加到html页面的head部分。然后,您将需要为元字段解析dom以正确地填充它们。
https://stackoverflow.com/questions/68677306
复制相似问题