Generating the Client Assertion JWT for private_key_jwt Authentication with Ruby

Featured image for sharing metadata for article

OpenID Connect Core 1.0 defines the private_key_jwt authentication method that can be used to authenticate the client with an Authorization Server's token endpoint.

This is a much better method to authenticate a client compared to a shared secret such as a client_secret, as it reduces risk of a credential being leaked on either side of the connection, as well as making rotation of those credentials easier - as only one party needs to be involved.

But it can be a pain to generate these for testing, as the client assertion that needs to be signed has a specific format.

I've come up with the following script, which can be run as follows:

ruby pkj.rb client_id https://authorization.server:443/path /path/to/signing.pem
ruby pkj.rb client_id https://authorization.server:443/path /path/to/signing.pem 1800 # for an optional expiration limit

This builds upon the json-jwt signing implementation from Creating Signed JWTs (JWS) with Ruby:

require 'jwt'
require 'securerandom'

client_id = ARGV[0]
aud = ARGV[1]
signing_key = OpenSSL::PKey.read(File.read ARGV[2])
token_lifetime = ARGV[3] || 1800

iat = Time.now.to_i

payload = {
  iss: client_id,
  sub: client_id,
  aud: aud,
  iat: iat,
  exp: iat + token_lifetime,
}

puts JWT.encode payload, signing_key, 'RS256'

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 #oidc.

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.