How to verify JWT Access Token from Azure AD in Ruby

Viewed 237

I am trying desperately to verify a JWT access token from Azure AD.

The error being raised is JWT::VerificationError (Signature verification raised)

Here is my code below in it's entirety edited to run as a script so it can be copy/pasted into a terminal. It is based on the Auth0 implementation.

The constant MY_SUPER_SECRET_ACCESS_TOKEN needs to be set to an access token from Azure AD.

require 'net/http'
require 'uri'

access_token = MY_SUPER_SECRET_ACCESS_TOKEN

jwks_raw = Net::HTTP.get URI('https://login.microsoftonline.com/common/discovery/v2.0/keys')

jwks_hash = Hash[
      jwks_keys
      .map do |k|
        [
          k['kid'],
          OpenSSL::X509::Certificate.new(
            Base64.decode64(k['x5c'].first)
          ).public_key
        ]
      end
    ]

token_info = JWT.decode(access_token, nil, false, {algorithm: 'RS256'})

cert_public_key = jwks_hash[token_info[1]['kid']]

JWT.decode(access_token, cert_public_key, true, algorithms: 'RS256')

This raises a Signature error? I'm not super great at any of this and we were using Auth0 with a very similar setup.

Is there some obvious fundamental step that I'm missing? Thanks

1 Answers

I was able to verify a JWT from Azure with the following. Also could look at using a solution suggested here

id_token # issuer https://login.microsoftonline.com/{tenant-id}/v2.0

jwks = JSON.parse(Net::HTTP.get URI('https://login.microsoftonline.com/common/discovery/v2.0/keys'))

JWT.decode(id_token, nil, true, { algorithms: ['RS256'], jwks: jwks})
Related