Rails API - Authentication with JWT

Episode #51 by Teacher's Avatar David Kimura

Summary

Using the knock gem, we will add JWT Authentication to our Rails API Application.
rails api json authentication 7:31

Resources

Summary

# Gemfile
gem 'knock'

# Bash
rails generate knock:install
rails generate knock:token_controller user

# api/application_controller.rb
module Api
  class ApplicationController < ActionController::API
    include Knock::Authenticable
    undef_method :current_user
  end
end

# user.rb
class User < ApplicationRecord
  ...
  alias_method :authenticate, :valid_password?

  def self.from_token_payload(payload)
    self.find payload["sub"]
  end
end

# api/users_controller.rb
module Api
  class UsersController < Api::ApplicationController
    before_action :authenticate_user
    ...
  end
end

# cURL Authentication
curl -X POST "http://api.demo.dev/user_token" -d '{"auth": {"email": "john.doe@example.com", "password": "123456"}}' -H "Content-Type: application/json"

{"jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NzczNjU5MjYsInN1YiI6MX0.77pG0_NrD8neDRqA-lHGfLdc8Xs65oPW1CL5lXmzx40"}

# cURL GET User
curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NzczNjU5MjYsInN1YiI6MX0.77pG0_NrD8neDRqA-lHGfLdc8Xs65oPW1CL5lXmzx40" http://api.demo.dev/users/1

{"id":1,"first_name":"John","last_name":"Doe","email":"john.doe@example.com","edit_link":"http://api.demo.dev/users/1/edit","phones":[{"name":"Home","phone_number":"888-555-1234"}]}