Skip to content

Instantly share code, notes, and snippets.

@craigplummer
Last active February 21, 2022 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigplummer/e476c8d53111c4259a01 to your computer and use it in GitHub Desktop.
Save craigplummer/e476c8d53111c4259a01 to your computer and use it in GitHub Desktop.
Azure AD API Auth Setup
config.middleware.insert_after ActionDispatch::ParamsParser, Warden::Manager do |manager|
manager.default_strategies :azure_ad_json_web_token
manager.failure_app = UnauthorizedController
end
class AzureAdJsonWebToken
def self.rsa_key
url = URI.parse('https://login.windows.net/common/discovery/keys')
key_file = JSON.parse(Net::HTTP.get(url))
x5c = Base64.decode64(key_file['keys'][0]['x5c'][0])
OpenSSL::X509::Certificate.new(x5c).public_key
end
def self.aud
ENV['aud']
end
def self.iss
ENV['iss']
end
def self.decode(token)
JWT.decode(token, rsa_key, true, { algorithm: 'RS256',
aud: aud,
verify_aud: true,
iss: iss,
verify_iss: true })
end
end
require 'azure_ad_json_web_token'
class AzureAdJsonWebTokenStrategy < ::Warden::Strategies::Base
def valid?
token
end
def authenticate!
if claims
success! claims
else
fail!
end
end
def claims
::AzureAdJsonWebToken.decode(token)[0]
rescue
nil
end
def token
unless request.env['HTTP_AUTHORIZATION'].nil?
request.env['HTTP_AUTHORIZATION'].split(' ').last
end
end
end
gem 'jwt', '~> 1.5.0'
gem 'warden', '~> 1.2.0'
require Rails.root.join('lib/strategies/azure_ad_json_web_token_strategy')
Warden::Strategies.add(:azure_ad_json_web_token, AzureAdJsonWebTokenStrategy)
module WardenHelper
extend ActiveSupport::Concern
included do
helper_method :warden, :current_user
prepend_before_filter :authenticate!
end
def current_user
warden.user
end
def warden
request.env['warden']
end
def authenticate!
warden.authenticate!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment