Bird
Raised Fist0
Ruby on Railsframework~8 mins

OAuth integration basics in Ruby on Rails - Performance & Optimization

Choose your learning style10 modes available
Performance: OAuth integration basics
MEDIUM IMPACT
OAuth integration affects page load speed mainly during the initial authentication redirect and token exchange phases.
Implementing OAuth login flow in a Rails app
Ruby on Rails
class SessionsController < ApplicationController
  def create
    # Use asynchronous background job for token exchange
    OAuthTokenJob.perform_later(params.to_unsafe_h)
    redirect_to loading_path
  end
end
Delegates token exchange to background job, allowing immediate redirect and faster initial load.
📈 Performance GainReduces blocking time on main thread, improving LCP by 200-500ms
Implementing OAuth login flow in a Rails app
Ruby on Rails
class SessionsController < ApplicationController
  def create
    # Blocking synchronous HTTP call to OAuth provider
    response = Net::HTTP.post_form(URI('https://oauth.provider.com/token'), params)
    user_info = JSON.parse(response.body)
    # Heavy processing before redirect
    process_user_data(user_info)
    redirect_to root_path
  end
end
Synchronous HTTP calls block the server thread, delaying response and increasing LCP.
📉 Performance CostBlocks rendering for 200-500ms depending on network latency
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous token exchange in controllerMinimal0Low but delayed by network[X] Bad
Asynchronous token exchange with background jobMinimal0Low and immediate[OK] Good
Rendering Pipeline
OAuth integration involves redirecting the user to the provider, waiting for token exchange, and then rendering the app page. Blocking operations during token exchange delay the Style Calculation and Layout stages.
→Network
→Style Calculation
→Layout
→Paint
⚠️ BottleneckNetwork blocking during synchronous token exchange
Core Web Vital Affected
LCP
OAuth integration affects page load speed mainly during the initial authentication redirect and token exchange phases.
Optimization Tips
1Avoid synchronous HTTP calls during OAuth token exchange in request cycle.
2Use background jobs or asynchronous processing for token handling.
3Minimize redirects and blocking operations to improve LCP.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with synchronous OAuth token exchange in Rails controllers?
AIt blocks the server thread, delaying response and increasing LCP
BIt increases DOM nodes and causes layout thrashing
CIt causes excessive CSS recalculations
DIt adds large JavaScript bundles to the page
DevTools: Performance
How to check: Record a performance profile during OAuth login flow. Look for long tasks blocking the main thread during token exchange.
What to look for: Long blocking tasks or network delays causing increased LCP and delayed first paint

Practice

(1/5)
1. What is the main purpose of using OAuth in a Rails application?
easy
A. Encrypt user passwords stored in the database
B. Allow users to log in using credentials from other services without sharing passwords
C. Automatically generate user passwords
D. Manage database migrations securely

Solution

  1. Step 1: Understand OAuth's role

    OAuth allows users to authenticate using external services like Google or Facebook without sharing their passwords with your app.
  2. Step 2: Identify the correct purpose in Rails context

    In Rails, OAuth integration is mainly for user login via third-party providers, not for password encryption or database tasks.
  3. Final Answer:

    Allow users to log in using credentials from other services without sharing passwords -> Option B
  4. Quick Check:

    OAuth = External login without password sharing [OK]
Hint: OAuth = login via other services, no password sharing [OK]
Common Mistakes:
  • Confusing OAuth with password encryption
  • Thinking OAuth generates passwords
  • Assuming OAuth manages database migrations
2. Which of the following is the correct way to add OmniAuth middleware for GitHub in a Rails app's config/initializers/omniauth.rb file?
easy
A. OmniAuth.configure do |config| config.provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end
B. Rails.middleware.add OmniAuth::GitHub, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
C. Rails.application.middleware.insert OmniAuth::Builder, :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
D. Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end

Solution

  1. Step 1: Recall OmniAuth middleware setup syntax

    The standard way is to use Rails.application.config.middleware.use OmniAuth::Builder with a block specifying providers.
  2. Step 2: Match the correct syntax for GitHub provider

    The block should call provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] inside the middleware use call.
  3. Final Answer:

    Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end -> Option D
  4. Quick Check:

    Middleware use with provider block = Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end [OK]
Hint: Use middleware.use with a block for providers [OK]
Common Mistakes:
  • Using incorrect middleware methods like add or insert
  • Misplacing provider call outside the block
  • Wrong OmniAuth configuration syntax
3. Given this simplified controller code handling OAuth callback, what will session[:user_id] be set to if the user is found?
def github
  auth = request.env['omniauth.auth']
  user = User.find_by(uid: auth['uid'], provider: auth['provider'])
  if user
    session[:user_id] = user.id
    redirect_to root_path
  else
    redirect_to login_path
  end
end
medium
A. The user's database ID
B. The OAuth provider name
C. The user's email address
D. Nil, because session is not set

Solution

  1. Step 1: Analyze user lookup and session assignment

    The code finds a user by UID and provider from OAuth data. If found, it sets session[:user_id] to user.id.
  2. Step 2: Understand what user.id represents

    This is the user's unique database ID, used to track logged-in users in the session.
  3. Final Answer:

    The user's database ID -> Option A
  4. Quick Check:

    session[:user_id] = user.id means database ID [OK]
Hint: Session user_id stores database user ID after login [OK]
Common Mistakes:
  • Confusing session user_id with provider or email
  • Assuming session is not set
  • Misreading user lookup logic
4. Identify the error in this OAuth callback method:
def google
  auth = request.env['omniauth.auth']
  user = User.find_or_create_by(uid: auth['uid']) do |u|
    u.email = auth['info']['email']
    u.provider = auth['provider']
  end
  session[:user_id] = user.id
  redirect_to root_path
end
medium
A. Missing provider in find_or_create_by conditions causes duplicate users
B. Using find_or_create_by with a block is invalid syntax
C. Accessing auth['info']['email'] should be auth['email']
D. Session assignment should happen before user creation

Solution

  1. Step 1: Check find_or_create_by conditions

    The method only uses uid: auth['uid'] to find or create a user, missing provider in the lookup.
  2. Step 2: Understand impact of missing provider

    Without provider, users with same UID from different providers may be treated as the same user, causing duplicates or wrong matches.
  3. Final Answer:

    Missing provider in find_or_create_by conditions causes duplicate users -> Option A
  4. Quick Check:

    Include provider in find_or_create_by to avoid duplicates [OK]
Hint: Always include provider with uid in find_or_create_by [OK]
Common Mistakes:
  • Thinking block with find_or_create_by is invalid
  • Misreading auth hash structure
  • Assuming session order causes error
5. You want to support login via multiple OAuth providers (Google, GitHub) in your Rails app. Which approach correctly handles user creation to avoid duplicate accounts when the same email is used across providers?
def oauth_callback
  auth = request.env['omniauth.auth']
  user = User.find_by(email: auth['info']['email'])
  if user
    # What should happen here?
  else
    user = User.create(
      email: auth['info']['email'],
      uid: auth['uid'],
      provider: auth['provider']
    )
  end
  session[:user_id] = user.id
  redirect_to root_path
end
hard
A. Ignore provider and uid, just use email for login
B. Create a new user regardless, to keep providers separate
C. Update user's uid and provider if missing, to link accounts
D. Raise an error if email exists to prevent duplicates

Solution

  1. Step 1: Understand the problem of duplicate accounts

    Users may log in with different providers but same email. Creating new users each time causes duplicates.
  2. Step 2: Best practice is to link accounts

    If a user with the email exists, update their uid and provider fields if missing to link OAuth data to one account.
  3. Final Answer:

    Update user's uid and provider if missing, to link accounts -> Option C
  4. Quick Check:

    Link accounts by updating uid/provider on existing email [OK]
Hint: Link accounts by updating uid/provider on existing email [OK]
Common Mistakes:
  • Creating new users for each provider causing duplicates
  • Ignoring provider and uid fields
  • Raising errors instead of linking accounts
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard