Added /api/public_key endpoint for verification of JWTs

pull/241/head
Rick Carlino 2016-03-23 11:41:58 -05:00
parent 6ef74ccfaf
commit 1381b577d6
8 changed files with 51 additions and 3 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.pem
*.gem
*.rbc
.bundle

View File

@ -27,7 +27,7 @@ This Repo is the Web based side of FarmBot. It allows users to control the devic
0. `rails s`
0. Go to `http://localhost:3000`
# Provisioning your own with Dokk
# Provisioning your own with Dokku
0. Get a Dokku instance running. HINT: DigitalOcean offers one click images.
0. Run `dokku plugin:install https://github.com/dokku/dokku-mongo.git mongo` on the server.

View File

@ -0,0 +1,13 @@
# RESTful endpoint for knowing the web APIs public key. You will need this to
# Verify authenticity of JSON Web Tokens issued to you.
module Api
class PublicKeysController < Api::AbstractController
skip_before_action :authenticate_user!, only: :show
PUBLIC_KEY = KeyGen.current.public_key.to_text
# GET /api/public_key
def show
render text: PUBLIC_KEY
end
end
end

View File

@ -1,6 +1,7 @@
FarmBot::Application.routes.draw do
namespace :api, defaults: {format: :json} do
resource :public_key, only: [:show]
resource :tokens, only: [:create]
resource :users, only: [:create]
resource :device, only: [:show, :destroy, :create, :update]

View File

@ -3,4 +3,4 @@
development:
secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
test:
secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
secret_key_base: 3b7cd727ee24e8444053437c36cc66c3

23
lib/key_gen.rb 100644
View File

@ -0,0 +1,23 @@
# Service for creating key pairs for cryptographically secure operations.
# Mostly used for creation of jwt.pem- which is used to verify authenticity of
# JSON Web Tokens
class KeyGen
SAVE_PATH = "jwt.#{Rails.env}.pem"
def self.run(path = SAVE_PATH)
rsa = OpenSSL::PKey::RSA.generate(2048)
File.open(path, 'w') { |f| f.write(rsa.to_pem) }
return rsa
end
# Heroku users can't store stuff on the file system.
# For them, there's maybe_load_from_env.
# Stores the *.pem file in an ENV var.
def self.maybe_load_from_env
OpenSSL::PKey::RSA.new(ENV['RSA_KEYS']) if ENV['RSA_KEYS']
end
def self.current
@current ||= ( maybe_load_from_env || self.run)
end
end

View File

@ -19,6 +19,7 @@ class SessionToken
iat: iat,
jti: SecureRandom.uuid, # TODO: Add ability to revoke.
iss: ISSUER,
exp: exp)
exp: exp,
alg: "RS256")
end
end

View File

@ -0,0 +1,9 @@
require_relative '../key_gen'
namespace :keys do
desc "Reset RSA keys used for signing / verifying tokens."
task generate: :environment do
puts KeyGen.run.to_pem
puts "Saved in '#{KeyGen::SAVE_PATH}'."
end
end