NTML authentication for Rails from inside Microsoft™ ActiveDirectory

I ended up with a decent setup in which the whole authentication is handled by IIS on a Windows machine that lives inside the ActiveDirectory tree. Adapting from these instructions.

IIS will act as a reverse proxy to your Rails app (typically installed on a *nix server, apache+passenger in my case).

The secret resides in configuring IIS to handle NTLM and then adding this nifty plugin that will basically reproduce the mod_proxy api for IIS.

Here’s an iirf.ini example:

# NOTE: 
# This file should be placed in the IIS document root 
# for the application

StatusInquiry ON
RewriteLogLevel 3
RewriteLog ....TEMPiirf
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [L]
ProxyPass ^/(.*)$ http://1.2.3.4:80/$1
ProxyPassReverse / http://1.2.3.4/

With this setup you can rely on the fact that the authentication is performed by IIS and you only get authenticated request with the authentication information stored inside HTTP_AUTHORIZATION.

To parse the user data from the auth header I used net-ntlm:

require 'kconv'
require 'net/ntlm'

if /^(NTLM|Negotiate) (.+)/ =~ env["HTTP_AUTHORIZATION"]
  encoded_message = $2
  message = Net::NTLM::Message.decode64(encoded_message)
  user = Net::NTLM::decode_utf16le(message.user)
end

After that you can even connect to the LDAP ActiveDirectory interface and fetch details about the user.