在 ruby 中存储 JWT 的最佳方式

The best way to store a JWT in ruby

我目前正在将我们的系统与外部 api 集成。我正在使用 httparty 来促进集成。

当我使用外部-api 进行身份验证时,我们会得到一个 JWT,是否有最佳实践来存储此 JWT 以供将来在 ruby 中的请求?

他们 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.

关于存储 JWT 的最佳实践,这实际上取决于您的用例,但对于您的情况,如果您的 JWT 具有典型的到期时间。这个想法是,在身份验证之后,您将令牌写入一个临时存储,如果您使用的是 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"))

在我的示例中,我假设您有一个客户端对象,其调用方法采用端点和选项哈希。但这应该让您对这里的方法有一个基本的了解。