gpt4 book ai didi

ruby-on-rails - 在rails API中使用omniauth-google-oauth2

转载 作者:行者123 更新时间:2023-12-03 08:32:19 26 4
gpt4 key购买 nike

我正在尝试在 Rails API 中实现从 google 登录的功能。

我将此行添加到我的 device.rb

config.omniauth :google_oauth2, Rails.application.credentials.dig(:google, :google_client_id),
Rails.application.credentials.dig(:google, :google_client_secret), scope: 'userinfo.email,userinfo.profile'

我还在我的凭据中添加了客户端 ID 和 key 。

这是我的 Google 函数

def google
@user = User.from_omniauth(request.env["omniauth.auth"])
end

这是我来自 User.rb 的 from_omniauth 函数

def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end

当我实现一个 API 时,我不知道应该使用 request.env["omniauth.auth"] 还是硬编码我从 OAuthPlayground 获得的访问 token 。如果我对 token 进行硬编码,如何从该 token 访问用户信息?

我还在我的应用程序中使用 Devise for Authentication,遵循本教程: https://www.digitalocean.com/community/tutorials/how-to-configure-devise-and-omniauth-for-your-rails-application

最佳答案

希望你一切都好。

最后,我得到了解决方案,因为我很困惑如何从前端收到的 token_id 中获取数据,因为从前端发送姓名和电子邮件不是有效的方式,因为任何人都可以更改它并且可能会使用错误的姓名和电子邮件地址进行注册。

在此之后添加 gem Httparty进入您的 Gemfile。

您可以通过google从前端获取这个token_id,也可以通过Google-OAuthplayground获取这个token_id用于测试目的并且可以由 postman 测试。

现在在用户 Controller 中添加功能

require 'httparty'                                                             
require 'json'
class UsersController < ApplicationController
include HTTParty

def google_oauth2
url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=#{params["id_token"]}"
response = HTTParty.get(url)
@user = User.create_user_for_google(response.parsed_response)
tokens = @user.create_new_auth_token
@user.save
render json:@user
end
end

或者通过使用 access_token 获取用户信息,您可以将 URL 替换为

url = "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=#{params["access_token"]}"

并将以下函数添加到您的 User.rb

def self.create_user_for_google(data)                  
where(uid: data["email"]).first_or_initialize.tap do |user|
user.provider="google_oauth2"
user.uid=data["email"]
user.email=data["email"]
user.password=Devise.friendly_token[0,20]
user.password_confirmation=user.password
user.save!
end
end

现在只需点击 postman 的 URL & 我希望一切都会正常。如果您有任何疑问,请发表评论。

注意:此解决方案仅适用于创建 Rails API 时的后端。

关于ruby-on-rails - 在rails API中使用omniauth-google-oauth2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64763522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com