Java code for NTLM User Identification
The following code perfrom NTLM Identification (NOT authentication) of a Windows user connecting to a Java Web app.
This will happen automatically only using IE as the client. With Firefox for example the username will be asked through pop-up, and then used by the web-app (again, this code doesn’t perform authentication…)
The original code come from jGuru
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
String auth = request.getHeader("Authorization"); if (auth == null) { response.setStatus(response.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NTLM"); response.flushBuffer(); return; } if (auth.startsWith("NTLM ")) { byte[] msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5)); int off = 0, length, offset; if (msg[8] == 1) { byte z = 0; byte[] msg1 = {(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S', (byte)'S', (byte)'P', z,(byte)2, z, z, z, z, z, z, z,(byte)40, z, z, z, (byte)1, (byte)130, z, z,z, (byte)2, (byte)2, (byte)2, z, z, z, z, z, z, z, z, z, z, z, z}; response.setHeader("WWW-Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1)); response.sendError(response.SC_UNAUTHORIZED); return; } else if (msg[8] == 3) { off = 30; length = msg[off+17]*256 + msg[off+16]; offset = msg[off+19]*256 + msg[off+18]; String remoteHost = new String(msg, offset, length,"UTF-16LE"); length = msg[off+1]*256 + msg[off]; offset = msg[off+3]*256 + msg[off+2]; String domain = new String(msg, offset, length,"UTF-16LE"); length = msg[off+9]*256 + msg[off+8]; offset = msg[off+11]*256 + msg[off+10]; String username = new String(msg, offset, length,"UTF-16LE"); out.println("Username:"+username+"<br />"); out.println("RemoteHost:"+remoteHost+"<br />"); out.println("Domain:"+domain+"<br />"); } } |
My little contribute is the following
- first of all telling that i’ve tested this code and it works (Tomcat 6, IE 6)
-
second, i changed the lines like
String username = new String(msg, offset, length);
toString username = new String(msg, offset, length,"UTF-16LE");
to remove blank spaces from the useful strings
-
clarify that this is only needs for identificating the user, do not use in a secure environment. If you need authenticating take a look to jCifs project