Skip to content

Instantly share code, notes, and snippets.

@cthornton
Last active August 29, 2015 14:03
Show Gist options
  • Save cthornton/e0db867727b0c19e7661 to your computer and use it in GitHub Desktop.
Save cthornton/e0db867727b0c19e7661 to your computer and use it in GitHub Desktop.
Sample JWT Authentication
class ApiController < ActionController::Base
attr_reader :current_user
before_action :set_current_user_from_jwt_token
def set_current_user_from_jwt_token
# Step 1: decode the JWT and get the user ID without checking
# the signature. Note JWT tokens are *not* encrypted, but signed.
payload = JWT.decode(request.authorization, nil, false)
# Step 2: See if the user exists in the database
@current_user = User.find(payload['user_id'])
# Step 3: Actually check to see if the JWT is signed correctly.
# Will raise an JWT::DecodeError if the signature is not valid.
JWT.decode(request.authorization, current_user.api_secret)
# Step 4: Check the "iat" and "exp" times to make sure this
# token was generated within this two second timeframe.
# Prevents replaying the same access token.
now = Time.now.to_i
if payload['iat'] > now || payload['exp'] < now
# Render some error indicating that the token has expired,
# and render a 401
end
rescue JWT::DecodeError
# Display some error message and render a 401
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment