Difference between JWT and OAuth in Ruby on Rails
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
- Facebook:
omniauth-facebook
- GitHub:
omniauth-github
- Google:
omniauth-google-oauth2
- Twitter:
omniauth-twitter
- LinkedIn:
omniauth-linkedin
- Instagram:
omniauth-instagram
- Amazon:
omniauth-amazon
- Slack:
omniauth-slack
- Microsoft:
omniauth-microsoft
- Dropbox:
omniauth-dropbox
- Salesforce:
omniauth-salesforce
- Stripe:
omniauth-stripe
- PayPal:
omniauth-paypal
- Twitch:
omniauth-twitch
- Spotify:
omniauth-spotify
- Discord:
omniauth-discord
- Yammer:
omniauth-yammer
- Zendesk:
omniauth-zendesk
- Shopify:
omniauth-shopify
- Reddit:
omniauth-reddit