module Oauth2Token

Constants

VERSION

Public Class Methods

get_token(client_id, client_secret, options={}) click to toggle source
# File lib/oauth2_token.rb, line 9
def get_token(client_id, client_secret, options={})
  begin
    endpoint = get_endpoint(options['uri'], "create")
    jwt = create_jwt(client_id, client_secret, endpoint, options['realm'])
    body = {
      "grant_type"            => "client_credentials",
      "scope"                 => options['scope'],
      "realm"                 => options['realm'],
      "client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      "client_assertion"      => jwt
    }
    response = wrap(HTTParty.post(endpoint, http_options.merge(:body => body)))
    response['access_token']
  rescue Exception => e
    raise e, "unable to fetch token for #{client_id}"
  end
end
is_token_active?(token, options={}) click to toggle source
# File lib/oauth2_token.rb, line 27
def is_token_active?(token, options={})
  begin
    endpoint = get_endpoint(options['uri'], "validate")
    body = {
      "token" => token,
      "realm" => options['realm']
    }
    response = wrap(HTTParty.post(endpoint, http_options.merge(:body => body)))
    response['active']
  rescue Exception => e
    raise "Unable to validate token. #{e.backtrace}"
  end
end
Also aliased as: is_token_valid?
is_token_valid?(token, options={})
Alias for: is_token_active?

Private Class Methods

create_jwt(client_id, client_secret, endpoint, realm) click to toggle source

TODO: Implement method to retrieve token details

# File lib/oauth2_token.rb, line 47
def create_jwt(client_id, client_secret, endpoint, realm)
  iat = Time.now.to_i
  exp = iat+600
  payload = {
    :iss => client_id,
    :sub => client_id,
    :aud => endpoint + '?realm=' + realm,
    :iat => iat,
    :exp => exp
  }
  JWT.encode payload, client_secret, 'HS256'
end
get_endpoint(uri, action) click to toggle source
# File lib/oauth2_token.rb, line 60
def get_endpoint(uri, action)
  case action
    when "create"
      return uri + "/oauth2/access_token"
    when "validate"
      return uri + "/oauth2/introspect"
  end
end
http_options(bearer = "") click to toggle source
# File lib/oauth2_token.rb, line 76
def http_options(bearer = "")
  options = {:headers => {
      'Content-Type' => 'application/x-www-form-urlencoded',
      'Accept'       => 'application/json'}
  }
  unless bearer.empty?
    options[:headers].merge!('Authorization' => 'Bearer ' + bearer)
  end
  options
end
wrap(response) click to toggle source
# File lib/oauth2_token.rb, line 69
def wrap(response)
  if (response.code != 200)
    raise("Error: #{response.inspect}")
  end
  JSON.parse(response.body)
end