JWTS and Bearer Tokens - katman22/pumanawa_kam GitHub Wiki

JWT and Bearer Tokens

Authentication in the API is handled by JWTs. Our application has its secret with which it can create keys.

Installation:

gem 'jwt'

Setup a helper.

app/lib/json_web_token.rb

class JsonWebToken SECRET_KEY = Rails.application.secret_key_base

def self.encode(payload, exp = 24.hours.from_now) payload[:exp] = exp.to_i JWT.encode(payload, SECRET_KEY) end

def self.decode(token) body = JWT.decode(token, SECRET_KEY)[0] HashWithIndifferentAccess.new body rescue JWT::DecodeError => e raise StandardError.new("Invalid token: #{e.message}") end end

Create a Secret

Manual generation

require 'jwt'

payload = { app: "my_expo_app", exp: 5.years.from_now.to_i } token = JWT.encode(payload, Rails.application.credentials.jwt_secret || ENV['JWT_SECRET']) puts token