Rails 6 앱용 Devise로 Facebook 인증 구현
이번 주에는 Rails 앱에 Facebook 인증을 설정하는 방법에 대해 글을 쓸 예정입니다.
전제 조건
페이스북 인증
Facebook 인증을 구현하려면 나중에 devise omniauth를 설정하기 위해
APP_ID
및 APP_SECRET
를 생성할 앱을 Facebook에 만들어야 합니다.페이스북 앱 만들기
My Apps
를 클릭합니다.Add a new App
를 클릭하세요.
For Everything Else
옵션을 선택합니다.
App Display Name
를 추가하고 Create App Id
버튼을 클릭합니다.

Setting
를 클릭한 다음 Basic
를 클릭합니다. APP_ID
및 APP_SECRET
를 볼 수 있어야 합니다. 나중을 위해 복사하고 저장하십시오.
App domains
에 localhost
를 추가합니다. 추가 아이콘이 있는 경우 추가 아이콘을 추가할 수도 있습니다.
Add Platform
를 클릭합니다.
Website
를 선택합니다.
http://localhost

장치에서 Facebook 인증 설정
이 섹션에서는 레일스 앱에서 페이스북 인증을 설정합니다.
gem 'omniauth-facebook'
bundle install
facebook
또는 google
를 등록하는 데 사용하는 공급자를 저장합니다.$ rails g migration AddOmniauthToUsers provider:string uid:string
rake db:migrate
APP_ID
및 APP_SECRET
를 포함하도록 장치 초기화 파일을 업데이트해야 합니다.# config/initializers/devise.rb
config.omniauth :facebook, "APP_ID", "APP_SECRET"
참고: 자격 증명을 사용하여 환경 변수를 저장하도록 선택한 경우. 이 명령을 사용하여 코드 편집기에서 편집할 수 있습니다. 터미널에서 이 코드를 실행합니다. vscode를 사용하지 않는 경우
code
부분을 코드 편집기로 변경하십시오.$ `EDITOR="code --wait" bin/rails credentials:edit`
해독된 자격 증명 파일에서 app_id 및 app_secret을 추가합니다.
facebook:
APP_ID: '<facebook_app_id>'
APP_SECRET: '<facebook_app_secret>'
따라서 이니셜라이저 파일 업데이트는
config.omniauth :facebook, Rails.application.credentials.facebook[:APP_ID], Rails.application.credentials.facebook[:APP_SECRET], token_params: { parse: :json }
# app/models/user.rb
devise :omniauthable, omniauth_providers: %i[facebook]
# app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"].except(:extra) # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
user
모델로 돌아가서 from_omniauth
self 메서드를 추가합니다. 이 방법은 등록할 때 새 사용자를 찾거나 만듭니다. 사용자의 first_name과 last_name을 저장하는 name_split 부분.# app/models/user.rb
def self.from_omniauth(auth)
name_split = auth.info.name.split(" ")
user = User.where(email: auth.info.email).first
user ||= User.create!(provider: auth.provider, uid: auth.uid, last_name: name_split[0], first_name: name_split[1], email: auth.info.email, password: Devise.friendly_token[0, 20])
user
end
# config/routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
<%= link_to "Register with Facebook", user_facebook_omniauth_authorize_path %>
그러면 앱에 facebook 인증이 추가됩니다.
기타 인증
프로세스는 Google 인증과 매우 유사합니다. 앱에 대한 프로젝트를 생성한 다음 인증을 위한 자격 증명을 생성해야 합니다. Google 인증 및 omniauth-google gem에 대한 자격 증명을 생성하는 링크를 첨부하겠습니다.
Create credentials on google
Omniauth Google gem
의견 섹션에 의견과 작성 내용을 알려주십시오.
다음주까지
Reference
이 문제에 관하여(Rails 6 앱용 Devise로 Facebook 인증 구현), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nkemjiks/implementing-facebook-authentication-with-devise-for-your-rails-6-app-1p3b텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)