-
Notifications
You must be signed in to change notification settings - Fork 0
With devise and traditional rails
Rails IAM's authorization layer is authentication-agnostic. It does not require the built-in JWT authentication and works seamlessly with Devise or any authentication system that provides the current authenticated user.
This allows you to use Devise for authentication while using RailsIAM for authorization.
rails generate devise AccountAdd rails_iam to Gemfile and run rails generate rails_iam:install
Before running migration command, update your rails_iam configuration.
RailsIam.configure do |config|
config.user_class = 'Account'
config.current_user_method = :current_account
# exclude devise namespace controller
config.authorization.excluded_controller_patterns = [ /\ADevise::/ ]
endEnable only the authorization module in your base controller.
class ApplicationController < ActionController::Base
rails_iam :authorization
endTell devise model to act as rails_iam user model
class Account < ApplicationRecord
acts_as_rails_iam_user
endRailsIAM will now use the authenticated devise user when evaluating authorization rules.
class ProductsController < ApplicationController
before_action :authenticate_account!, except: [ :index ]
# also skip authorization for index
skip_authorization only: :index
authorize permissions: "product:show"
# public
def index; end
# permission: product:show
def show; end
end
# controller that is public from devise authentication, should be also free from rails_iam authorization
class PublicController < ApplicationController
skip_authorization
def index; end
end
# override :forbidden and :unauthorized exception in main controller
class ApplicationController < ActionController::Base
rails_iam :authorization
def render_rails_iam_authentication_error(exception)
flash[:alert] = exception.message
redirect_to new_account_session_path
end
def render_rails_iam_authorization_error(exception)
flash[:alert] = exception.message
redirect_to redirect_back
end
endWhen using Devise:
- Devise is responsible for authentication.
- RailsIAM is responsible for authorization.
- Configure
current_user_methodto:current_user. - Tell devise model to act as
rails_iamuser - Handle
AuthenticationErrorby redirecting to the Devise sign-in page. - Handle
AuthorizationErrorby redirecting to an appropriate page or displaying an access denied message.
This separation allows Rails IAM to integrate naturally into existing Devise applications without replacing or modifying the authentication workflow.