Validate JWT token in Ruby

This is a memo when verifying the AWS Cognito web token.

[JSON Web Token Verification -Amazon Cognito](https://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt. html)

Cognito allows you to download a JWK set for verification for each user pool

https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json

Gem to use

jwt jwt/ruby-jwt: A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.

Used to decode regular JWT tokens

json-jwt

nov/json-jwt: JSON Web Token and its family (JSON Web Signature, JSON Web Encryption and JSON Web Key) in Ruby

Used to create a public key from a public JSON web key (JWK)

Implementation

#Download JWK set
uri = "https://cognito-idp.ap-northeast-1.amazonaws.com/example/.well-known/jwks.json"
response = Net::HTTP.get_response(URI.parse(uri))
jwks = JSON.parse(response.body)

#Decode JWT without verification
token = JWT.decode(jwt, nil, false)

#Get the kid match from the JWK set
jwk = jwks["keys"].find { |obj| obj["kid"] == token[1]["kid"] }

#Create public key
public_key = JSON::JWK.new(jwk).to_key

#Exception when decoding verification using public key is invalid
JSON::JWT.decode(jwt, public_key)

If you find it helpful, please LGTM

Recommended Posts

Validate JWT token in Ruby
Class in Ruby
Heavy in Ruby! ??
About eval in Ruby
Output triangle in Ruby
Variable type in ruby
Fast popcount in Ruby
ABC177 --solving E in Ruby
Implemented XPath 1.0 parser in Ruby
Read design patterns in Ruby
Write class inheritance in Ruby
Update Ruby in Unicorn environment
Integer unified into Integer in Ruby 2.4
[Ruby] Exception handling in functions
Use ruby variables in javascript.
Multiplication in a Ruby array
About regular expressions in Ruby
Birthday attack calculation in Ruby
Judgment of fractions in Ruby
Find Roman numerals in Ruby
Try using gRPC in Ruby
[Ruby] Find numbers in arrays
NCk mod p in Ruby
Chinese Remainder Theorem in Ruby
Sorting hashes in a Ruby array
Basics of sending Gmail in Ruby
How to iterate infinitely in Ruby
Try to implement Yubaba in Ruby
Implementation of ls command in Ruby
Achieve 3-digit delimited display in Ruby
Encoding when getting in Windows + Ruby
Run GraphQL Ruby resolver in parallel
Ruby on Rails Japanese-English support i18n
[Ruby] Extracting double hash in array
[Ruby] then keyword and case in
How to install Bootstrap in Ruby
String output method memo in Ruby
Implement a gRPC client in Ruby
Write keys and values in Ruby
[Super Introduction] About Symbols in Ruby
Hanachan in Ruby (non-destructive array manipulation)
Manipulating data in GCS during Ruby
I tried using JWT in Java
Is there no type in Ruby?
Try file locking in Ruby directory
[Ruby] undefined method `dark?'occurs in rqr_code
openssl version information in ruby OPENSSL_VERSION
Ruby methods often used in Rails
Make Ruby segfault in two lines