Skip to content
Janko Marohnić edited this page Dec 8, 2021 · 15 revisions

To make Rodauth endpoints accessible via JSON API, enable the json feature:

# app/misc/rodauth_main.rb
class RodauthMain < Rodauth::Rails::Auth
  configure do
    # ...
    enable :json
    only_json? true # accept only JSON requests (optional)
    # ...
  end
end

This will store account session data into the Rails session. If you rather want stateless token-based authentication via the Authorization header, enable the jwt feature (which builds on top of the json feature) and add the JWT gem to the Gemfile:

$ bundle add jwt
# app/misc/rodauth_main.rb
class RodauthMain < Rodauth::Rails::Auth
  configure do
    # ...
    enable :jwt
    jwt_secret "<YOUR_SECRET_KEY>" # store the JWT secret in a safe place
    only_json? true # accept only JSON requests (optional)
    # ...
  end
end

The JWT token will be returned after each request to Rodauth routes. To also return the JWT token on requests to your app's routes, you can add the following code to your base controller:

class ApplicationController < ActionController::Base
  # ...
  after_action :set_jwt_token

  private

  def set_jwt_token
    if rodauth.use_jwt? && rodauth.valid_jwt?
      response.headers["Authorization"] = rodauth.session_jwt
    end
  end
  # ...
end
Clone this wiki locally