tumati tumati - 2 months ago 18
Ruby Question

decode ruby/jwt using pem certificate

I have public key in pem certificate
I'm trying decode JWT using that public key, getting error like wrong number of arguments passed
I know I have to use public key to decode but all I'm getting is certificate from open ssl

I think if I get the public key from open ssl certificate, issue might be resolved.
I'm not tried jwt openssl before, could someone help me on this

require 'jwt'

token='eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJHZXR0eSBTVFMiLCJzdWIiOiIxMjM0In0.nNqF_osgle1sXYvg4pUoU60LopG1ehhZm4ged0RpxID5bchtigyvK9JqS27qTGkJELg62liQPXo_0DkYV7tr3gRcuFFaq9WlmCmEfxF__dVfcDzHp5NThARZQdRzaBsbsAfLvCJHUwm0wiYmDuCXEieMDkl_BVwEXrfCNxXFRv8'

key = OpenSSL::X509::Certificate.new <<-PEM
-----BEGIN CERTIFICATE-----
MIICcDCCAdmgAwIBAgIJAL4W5EhxGIBlMA0GCSqGSIb3DQEBBQUAMFExCzAJBgNVBAYTAlVTMRUw
EwYDVQQKDAxHZXR0eSBJbWFnZXMxKzApBgNVBAMMImdldHR5aW1hZ2VzLnNlcnZpY2VzLnN0cy5z
aWduYXR1cmUwHhcNMTEwNjAyMjIxMjMzWhcNMTIwNjAxMjIxMjMzWjBRMQswCQYDVQQGEwJVUzEV
MBMGA1UECgwMR2V0dHkgSW1hZ2VzMSswKQYDVQQDDCJnZXR0eWltYWdlcy5zZXJ2aWNlcy5zdHMu
c2lnbmF0dXJlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCubFZQPFMhI1NtW17ZyyblqV9c
0SgVCj01x0quIhWaTXVCE9s2Ai9O5CDaj7syV4ItzJ0Ls8ynEjBN3tk2JC1uK93Y3+kCwuOOEo0M
2j0YV3gSFYrpPUurcWb6ZZhjaxu01zhs+bXnxT29UMoR4ctjjLTUqgdnthPMfa3MDhfARQIDAQAB
o1AwTjAdBgNVHQ4EFgQU9T4os8xazIB1o0zQtLvGOFqf85gwHwYDVR0jBBgwFoAU9T4os8xazIB1
o0zQtLvGOFqf85gwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBtkf1Qlw2F9X9DPp2w
xv9F+LB2peR9Qgn2YE2y28UcINOea037Zf8zPfC3pZ4aqGc6kHrQkZ/Vke2esOmBvebgdhZhiG71
Hpu0trgPTwHdO5B18CJ/QEEsDY10CD1dFUCyBEyONJLKCyhHwjYP6iuGotG2L6xB+xf3QHs+aRAI
/g==
-----END CERTIFICATE-----
PEM


decoded_token = JWT.decode token, key, true, { :algorithm => 'RS512' }

Answer

The certificate has a public_key method that gives you what you want:

# Assuming pem contains the pem encoded string
cert = OpenSSL::X509::Certificate.new(pem)
key = cert.public_key

decoded_token = JWT.decode token, key, true, { :algorithm => 'RS512' }