Skip to content
Marc Busqué edited this page Feb 21, 2017 · 5 revisions

Example applications

Sinatra

require 'sinatra'
require 'warden'
require 'warden/jwt_auth'
require 'singleton'

# A user record
class User
  include Singleton
  def jwt_subject
    1
  end
end

# User repository
class UserRepo
  def self.find_for_jwt_authentication(_sub)
    User.instance
  end
end

class RevocationStrategy
  def self.revoke_jwt(payload, user)
    # TODO: Do something to revoke a JWT token
  end

  def self.jwt_revoked?(payload, user)
    # TODO: Do something to check whether a JWT token is revoked
  end
end

Warden::JWTAuth.configure do |config|
  config.secret = 'super-secret'
  config.mappings = { default: UserRepo }
  config.dispatch_requests = [['POST', %r{^/login$}]]
  config.revocation_requests = [['DELETE', %r{^/logout$}]]
  config.revocation_strategies = { default: RevocationStrategy }
end

use Warden::JWTAuth::Middleware

use Warden::Manager do |manager|
  manager.default_strategies(:jwt)
  manager.failure_app = ->(_env) { [401, {}, ['unauthorized']] }
end

get '/protected' do
  env['warden'].authenticate!
  'Sensitive data'
end

post '/login' do
  # TODO: Check username / password
  env['warden'].set_user(User.instance, store: false)
  'Logged in'
end

delete '/logout' do
  'Logged out'
end
Clone this wiki locally