Creating Signed JWTs (JWS) with Ruby

Featured image for sharing metadata for article

When you're working with JSON Web Tokens (JWTs), you'll almost certainly be validating that the contents of the token is sent by the correct service by verifying the token's signature.

However, it's also helpful to be able to create these signed JWTs for yourself, which we can do with either of the two popular JWT libraries in Ruby.

With both of these approaches, the expectation is that you can run them as the following:

ruby sign.rb payload.json 'hmac-key-here'
ruby sign.rb payload.json 'hmac-key-here' 'HS256'
ruby sign.rb payload.json '/path/to/key.pem' 'RS256'
ruby sign.rb payload.json '/path/to/key.pem' 'ES256'

With JSON::JWT

Using JSON::JWT, we can use the following:

require 'json/jwt'

payload = JSON.parse(File.read ARGV[0])
maybe_secret = ARGV[1]
algorithm = ARGV[2] || 'HS256'

if File.exists? maybe_secret
  maybe_secret = OpenSSL::PKey.read(File.read maybe_secret)
end

puts JSON::JWT.new(payload).sign(maybe_secret, algorithm.to_sym)

With ruby-jwt

Using ruby-jwt, we have the following code:

require 'jwt'

payload = JSON.parse(File.read ARGV[0])
maybe_secret = ARGV[1]
algorithm = ARGV[2] || 'HS256'

if File.exists? maybe_secret
  maybe_secret = OpenSSL::PKey.read(File.read maybe_secret)
end

puts JWT.encode payload, maybe_secret, algorithm

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby #command-line #jwt #json.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.