Created
July 3, 2014 03:38
-
-
Save cthornton/1b919f13e7a20fa65173 to your computer and use it in GitHub Desktop.
Authentication with JWT and Redis (More Secure)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def set_current_user_from_jwt_token | |
# Verification steps from the previous example | |
payload = JWT.decode(request.authorization, nil, false) | |
@current_user = User.find(payload['user_id']) | |
JWT.decode(request.authorization, current_user.api_secret) | |
now = Time.now.to_i | |
if payload['iat'] > now || payload['exp'] < now | |
# Render a 401 and do not continue | |
end | |
# Now we can check to ensure this JWT token has never been used before, | |
# using some atomic operations from Redis | |
# The redis key we are interested in: <user id>:<one-time use token> | |
key = "#{payload['user_id']}:#{payload['jti']}" | |
# See if the key already exists in redis. If it does not exist it will | |
# return nil. If it does, it will return "1". This is atomic. | |
if redis.getset(key, "1") | |
# Render 401 and don't continue | |
# | |
end | |
# Make sure to expire the key, to prevent a massively long history of | |
# one-time use tokens. Give it an extra two seconds, just in case. | |
redis.expireat(key, payload['exp'] + 2) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment