Blunt

Blunt provides framework-agnostic authentication using JSON Web Tokens. It wraps ruby-jwt with an easy-to-use interface and some common conventions. Great for APIs.

Installation

Come on now:

gem 'blunt'
bundle install

Or:

gem install blunt

Usage

Add a secret key at ENV['BLUNT_SECRET']. You can generate one with Blunt.new_secret.

Signup

# inside your signup interactor
if digest = Blunt.(password, password_confirmation)
  # create user
else
  # trigger an error
end

Pretty straightforward: returns an encrypted password if the unencrypted inputs match, otherwise nil. You may want to validate the password first, e.g. minimum length.

Login

# inside your login controller
token = Blunt.(expected, attempted, claims)
  • expected is the user's encrypted password as stored in the database.
  • attempted is the unencrypted password attempt as sent by the client.
  • claims is a hash of JWT claims. It must contain a :sub key whose value is any unique way to identify the user. You can also send optional JWT claims with the payload, such as :exp. Refer to the ruby-jwt docs for more information.

If the passwords match and a :sub claim is present, a token will be generated for the claims. If the login attempt fails, the token will be nil. Have your controller return the token to the client and store it somewhere (cookies, local storage, etc).

Request Authentication

Pass the token from the client in a request header: 'HTTP_AUTHORIZATION' => 'Bearer <TOKEN>.

include Blunt::Controller in your controller class. current_user will memoize whatever is in :sub in the token's payload, or nil if there are any errors.

If the hash of request headers is not at request.env, you will need to override #_blunt_request_env to return it. (This works out of the box for Rails and Hanami.)

Logout

To logout, simply have the controller respond to the client with instructions to unset the token, wherever it is stored.