nsarno / knock

Seamless JWT authentication for Rails API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

undefined method `sign' for #<String:0x0000558a8137fcd8>

n2xnot opened this issue · comments

Hi,
I'm following the authentication example written in the README, but I can't make it works because it is failing with the following exception:

def authenticated_header(user)
  token = Knock::AuthToken.new(payload: { sub: user.id }).token
  { 'Authorization': "Bearer #{token}" }
end
NoMethodError:
  undefined method `sign' for #<String:0x000055e5be569c40>
# /usr/local/bundle/gems/jwt-1.5.6/lib/jwt.rb:47:in `sign_rsa'
# /usr/local/bundle/gems/jwt-1.5.6/lib/jwt.rb:38:in `sign'
# /usr/local/bundle/gems/jwt-1.5.6/lib/jwt.rb:96:in `encoded_signature'
# /usr/local/bundle/gems/jwt-1.5.6/lib/jwt.rb:106:in `encode'
# /usr/local/bundle/gems/knock-2.1.1/app/model/knock/auth_token.rb:14:in `initialize'

This is how my initializer looks:

Knock.setup do |config|
  config.token_audience = -> { Rails.application.credentials.auth0_client_id }
  config.token_signature_algorithm = 'RS256'
  config.token_secret_signature_key = -> { Rails.application.credentials.auth0_client_secret }
end

I will really appreciate it if someone can suggest me what's wrong with my code.

Hello again, I just resolved.
It was necessary to set OpenSSL::PKey::RSA Object to token_secret_signature_key when selecting RS256 algorithm.

Knock.setup do |config|
  config.token_audience = -> { Rails.application.credentials.auth0[:client_id] }
  config.token_signature_algorithm = 'RS256'
  rsa_private = OpenSSL::PKey::RSA.generate(2048)
  config.token_secret_signature_key = -> { rsa_private }
  jwks_row = Net::HTTP.get(URI.parse(Rails.application.credentials.auth0[:jwks]))
  jwks_keys = Array(JSON.parse(jwks_row)['keys'])
  config.token_public_key = OpenSSL::X509::Certificate.new(Base64.decode64(jwks_keys[0]['x5c'].first)).public_key
end

JWT Code(rsa)

def sign(to_sign)
  algorithm, msg, key = to_sign.values
  raise EncodeError, "The given key is a #{key.class}. It has to be an OpenSSL::PKey::RSA instance." if key.class == String
  key.sign(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), msg)
end