Difference between JWT and OAuth in Ruby on Rails

Vishal Pandey
3 min readApr 23, 2024

--

JWT (JSON Web Tokens) and OAuth are both used for authentication and authorization in Ruby on Rails applications, but they serve different purposes and operate at different levels of the authentication process.

JWT (JSON Web Tokens):

  • JWT is a compact, URL-safe means of representing claims to be transferred between two parties.
  • It is commonly used for authentication and exchanging claims between a client and a server.
  • JWT is a token-based authentication mechanism that includes encoded user information and is signed to ensure its integrity.
  • In Rails applications, JWT can be used as a stateless authentication mechanism, where the server generates a token containing user information upon successful authentication, and the client sends this token in subsequent requests to access protected resources.
  • JWT is typically used for single sign-on (SSO) and stateless authentication scenarios.
# Gemfile
gem 'jwt'
# config/initializers/jwt.rb
JWT_SECRET = 'your_secret_key'
# app/controllers/authentication_controller.rb
class AuthenticationController < ApplicationController
def login
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
token = encode_token(user_id: user.id)
render json: { token: token }
else
render json: { error: 'Invalid email or password' }, status: :unauthorized
end
end

private

def encode_token(payload)
JWT.encode(payload, JWT_SECRET)
end
end

# app/controllers/protected_resources_controller.rb
class ProtectedResourcesController < ApplicationController
before_action :authorized

def index
render json: { message: 'Protected resource accessed successfully' }
end

private

def authorized
token = request.headers['Authorization'].split(' ').last
begin
decoded_token = JWT.decode(token, JWT_SECRET)
@current_user = User.find(decoded_token[0]['user_id'])
rescue JWT::DecodeError
render json: { error: 'Invalid token' }, status: :unauthorized
end
end
end

OAuth (Open Authorization):

  • OAuth is an open standard for access delegation, commonly used for granting third-party applications limited access to a user’s resources without exposing their credentials.
  • OAuth is a protocol for authorization and not directly for authentication.
  • In Rails applications, OAuth is often used for allowing users to authenticate with external services (such as Google, Facebook, GitHub) and granting permissions to access their resources.
  • OAuth operates by delegating user authentication to the service provider (such as Google), which then provides an access token to the client application. This token is used by the client to access the user’s resources on the service provider’s behalf.
# Gemfile
gem 'omniauth-google-oauth2'
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, 'client_id', 'client_secret'
end
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.from_omniauth(request.env['omniauth.auth'])
session[:user_id] = user.id
redirect_to root_url, notice: 'Logged in successfully'
end

def destroy
session[:user_id] = nil
redirect_to root_url, notice: 'Logged out successfully'
end
end

# app/models/user.rb
class User < ApplicationRecord
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.save!
end
end
end

These examples demonstrate how to implement JWT-based authentication using the jwt gem and OAuth-based authentication using the omniauth-google-oauth2 gem in a Ruby on Rails application. Please note that the client_id and client_secret values need to be obtained from the respective OAuth provider (e.g., Google Developer Console) for OAuth authentication to work.

In summary, while both JWT and OAuth are used for authentication and authorization in Rails applications, JWT is primarily a token-based authentication mechanism for user authentication and stateless authorization, whereas OAuth is a protocol for granting third-party applications access to user resources with user consent. They can be used together in a Rails application to provide a secure and flexible authentication and authorization mechanism.

List of some popular OmniAuth

  1. Facebook: omniauth-facebook
  2. GitHub: omniauth-github
  3. Google: omniauth-google-oauth2
  4. Twitter: omniauth-twitter
  5. LinkedIn: omniauth-linkedin
  6. Instagram: omniauth-instagram
  7. Amazon: omniauth-amazon
  8. Slack: omniauth-slack
  9. Microsoft: omniauth-microsoft
  10. Dropbox: omniauth-dropbox
  11. Salesforce: omniauth-salesforce
  12. Stripe: omniauth-stripe
  13. PayPal: omniauth-paypal
  14. Twitch: omniauth-twitch
  15. Spotify: omniauth-spotify
  16. Discord: omniauth-discord
  17. Yammer: omniauth-yammer
  18. Zendesk: omniauth-zendesk
  19. Shopify: omniauth-shopify
  20. Reddit: omniauth-reddit

--

--

Vishal Pandey
Vishal Pandey

Written by Vishal Pandey

Senior Software Engineer@Thoughtworks

No responses yet