Skip to content

Instantly share code, notes, and snippets.

@hassox
Last active July 20, 2016 01:54
Show Gist options
  • Save hassox/43dd9492df78407e7e6cda4e1199762e to your computer and use it in GitHub Desktop.
Save hassox/43dd9492df78407e7e6cda4e1199762e to your computer and use it in GitHub Desktop.
devise jwtable
Devise.setup do |config|
config.warden do |manager|
manager.intercept_401 = false
manager.default_strategies(scope: :user).unshift :jwtable
end
end
module Devise
module Models
# To add jwtable to your User model add
# ```devise ...., :jwtablea```
module Jwtable
class Strategy < Devise::Strategies::Authenticatable
JWT_REG = /^Bearer:?\s+(.*?);?$/
def store
false
end
def valid?
request.headers['HTTP_AUTHORIZATION'].present?
end
def authenticate!
match = JWT_REG.match(request.headers['HTTP_AUTHORIZATION'])
if match.blank? || match[1].blank?
fail!('Authorization header required')
else
claims, user = user_and_claims_from_token(match[1])
env['jwt.claims'] = claims
success! user
end
rescue JWT::DecodeError, JWT::ExpiredSignature, JWT::VerificationError => e
fail!(e.message)
end
def user_and_claims_from_token(jwt)
claims = JWT.decode(jwt, Rails.application.secrets.jwt_secret).first
case claims['sub']
when /^User:\d+/
[claims, User.find(claims['sub'].split(':').last)]
else
[claims, nil]
end
end
end
end
end
end
# for warden, `:jwtable_strategy` is just a name to identify the strategy
Warden::Strategies.add :jwtable, Devise::Models::Jwtable::Strategy
Devise.add_module :jwtable, strategy: true
class User < ActiveRecord::Base
devise :database_authenticatable, :jwtable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment