The best way to store a JWT in ruby

Viewed 141

I am currently integrating our system, with an external api. I am using httparty to facilitate the integration.

When I do auth with the external-api we are provided with a JWT, is there a best practice for storing this JWT for future requests in ruby?

1 Answers

Thew JWT Ruby Gem should be your first choice for Ruby implementation. There are a few other Gems. For more information on JWT in general you may refer to the gem's documentation or perhaps here.

Regarding best practice for storing the JWT, it really depends on your use case, but for yours, it sounds like you'd want to use a temporary cache type store such as Redis if you're JWT has a typical expiration time. The ideas is that after authentication, you write the token to a temporary store, which might look like this if you were using Redis.

require 'redis'


my_jwt_token = call_some_api_to_get_token

redis = Redis.new (
    :host => 'hostname',
    :port => port,
    :password => 'password')

token_expires_in_seconds = 60 * 60 # set expire 1 hour
redis.set('my_jwt_token', my_jwt_token, ex: token_expires_in_seconds)

my_api_client.call('some_endpoint', jwt_token: redis.get('my_jwt_token"))

In my example I'm assuming you have a client object with a call method which takes an endpoint and the options hash. But this should give you a basic idea of an approach here.

Related