Skip to content

Instantly share code, notes, and snippets.

@bswinnerton
Last active September 3, 2015 21:23
Show Gist options
  • Save bswinnerton/5382ead035d89d38e815 to your computer and use it in GitHub Desktop.
Save bswinnerton/5382ead035d89d38e815 to your computer and use it in GitHub Desktop.
require 'jwt'
require 'warden'
class JWTStrategy < Warden::Strategies::Base
# All of the below constants would be defined in a configuration initializer
ENCRYPTION_ALGORITHM = 'HS256'
RETRIEVE_USER = Proc.new { |guid| User.find_by(user_guid: guid) }
SHARED_SECRET = 'kittens'
USER_IDENTIFIER_CLAIM = 'guid'
def valid?
!!jwt
end
def authenticate!
if user = RETRIEVE_USER.call(user_identifier)
success!(user)
else
fail!
end
end
private
def user_identifier
custom_claims.fetch(USER_IDENTIFIER_CLAIM)
end
def custom_claims
decoded_jwt.first
end
def reserved_claims
decoded_jwt.last
end
def decoded_jwt
JWT.decode(jwt, SHARED_SECRET, ENCRYPTION_ALGORITHM)
end
def jwt
return false unless authorization_header_components
authorization_header_components.last
end
def token_type
return false unless authorization_header_components
authorization_header_components.first
end
def authorization_header_components
return false unless authorization_header
authorization_header.match(/\A(Bearer) (.*)\z/).captures
end
def authorization_header
request.env['HTTP_AUTHORIZATION']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment