Android NTLM Authentication

阅读更多

 

http://stackoverflow.com/questions/15762237/negotiate-using-one-session-with-ntlm-authentication-at-android

 

http://www.tekritisoftware.com/android-ntlm-authentication

 

 

With the increasing usage of smart phone in our daily life, this usage is getting more quantitative as well as qualitative by each passing day. It started with basic telephony then gaming and now it has graduated to Apps which helps in managing and exchanging important data like mails, financial details, payrolls and many more. Such heavy exchanges from or to the outer world is done by interacting with different server through legacy communication protocols and that involves different types of authentication handshakes.

Recently we came across a requirement of communicating to a server which is using NTLM authentication protocol. Now some of you would think “What is NTLM” so here is the answer::

NTLM is a suite of Microsoft security protocol and is successor to the authentication protocol in Microsoft LAN Manager. It is used for the authentication and negotiation of secure DCE purpose.

NTLM Security Service Provider (NTLMSSP) implements some core operations and these are::

1) Authentication :: Clients would be able to prove their respective identities
2) Signing :: It provides digital “signature” security.
3) Sealing :: It keeps the data confidential by providing symmetric-Key encryption.

More about NTLM and its authentication mechanism can be read in details at

http://www.innovation.ch/personal/ronald/ntlm.html
http://davenport.sourceforge.net/ntlm.html#whatIsNtlm

Here is the solution for successfully authenticating and communicating with a server using NTLM authentication protocol:

Step 1: We need to have the JCIF library. 
JCIFS can be downloaded from: http://jcifs.samba.org/

 

Step 2: Create a class which is the AuthSchemeFactory interface:

             NTLMSchemeFactory.java:

 

package com.movit.util;

 

import org.apache.http.auth.AuthScheme;

import org.apache.http.auth.AuthSchemeFactory;

import org.apache.http.impl.auth.NTLMScheme;

import org.apache.http.params.HttpParams;

 

public class NTLMSchemeFactory implements AuthSchemeFactory {

    public AuthScheme newInstance(HttpParams params) {

        return new NTLMScheme(new JCIFSEngine());

    }

}

 

Step 3Create a class for acting as a NTLM engine interface, which does all the type message validation and verification.

JCIFSEngine.java

package com.movit.util;

 

import java.io.IOException;

 

import jcifs.ntlmssp.NtlmFlags;

import jcifs.ntlmssp.Type1Message;

import jcifs.ntlmssp.Type2Message;

import jcifs.ntlmssp.Type3Message;

 

import org.apache.http.impl.auth.NTLMEngine;

import org.apache.http.impl.auth.NTLMEngineException;

 

public class JCIFSEngine implements NTLMEngine {

    private static final int TYPE_1_FLAGS = NtlmFlags.NTLMSSP_NEGOTIATE_56 | NtlmFlags.NTLMSSP_NEGOTIATE_128

                                            | NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2

                                            | NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN

                                            | NtlmFlags.NTLMSSP_REQUEST_TARGET;

 

    public String generateType1Msg(String domain, String workstation) throws NTLMEngineException {

        final Type1Message type1Message = new Type1Message(TYPE_1_FLAGS, domain, workstation);

        return Base64.encode(type1Message.toByteArray());

    }

 

    public String generateType3Msg(String username, String password, String domain, String workstation, String challenge)

        throws NTLMEngineException {

        Type2Message type2Message;

 

        try {

            type2Message = new Type2Message(Base64.decode(challenge));

        } catch (final IOException exception) {

            throw new NTLMEngineException("Error in type2 message", exception);

        }

 

        final int type2Flags = type2Message.getFlags();

        final int type3Flags = type2Flags

                               & (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));

        final Type3Message type3Message = new Type3Message(type2Message, password, domain, username, workstation, type3Flags);

        return Base64.encode(type3Message.toByteArray());

    }

}

 

step 4. Register the NTLM Scheme Factory with HttpClient instance and other domain credentials to do the handshake. It has been observed that deviceIP and domainName is not required on a mandatory basis. These can be set as null also.

 

 

    /*

     * authentication method 7

     * webserviceUrl, 

     * url of the web service. 

     * webserviceIP, 

     * IP of the server.

     * username, Domain username 

     * password, Domain password

     */

    public int getFileSize(String webserviceUrl, String username, String password) {

        int fileSize = 0;

        try {

            String deviceIP = null;// getLocalIpAddress(); Device IP

            String domainName = FileUtils.DOMAIN_NAME;

 

            DefaultHttpClient httpclient = new DefaultHttpClient();

            httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());

            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);

            AuthScope authScope1 = new AuthScope(null, -1);

            httpclient.getCredentialsProvider().setCredentials(authScope,

                                                               new NTCredentials(username, password, deviceIP, domainName));

 

            HttpGet httpGet = new HttpGet(webserviceUrl);

            httpGet.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

 

            HttpResponse response = httpclient.execute(httpGet);

            // String responseXML = EntityUtils.toString(response.getEntity());

 

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

                HttpEntity entity = response.getEntity();

                //fileSize = (int) entity.getContentLength();

                fileSize = getfileSizeByInputStream(entity.getContent());

                entity.consumeContent();

                return fileSize;

            }

 

        } catch (Exception e) {

            e.printStackTrace();

        }

        return fileSize;

    }

 

    public int getfileSizeByInputStream(InputStream input) {

        BufferedInputStream bis = new BufferedInputStream(input);

        int progress = 0;

        try {

            int length;

            byte buffer[] = new byte[6 * 1024];

            while (-1 != (length = bis.read(buffer))) {

                progress += length;

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                if (null != bis) {

                    bis.close();

                    bis = null;

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return progress;

    }

 

    public String getLocalIpAddress() {

 

        String deviceIp = null;

        boolean keepLookupOn = true;

 

        try {

            Enumeration availableNetwork = NetworkInterface.getNetworkInterfaces();

 

            while (availableNetwork.hasMoreElements() && keepLookupOn) {

                NetworkInterface intf = (NetworkInterface) availableNetwork.nextElement();

                Enumeration enumIpAddr = intf.getInetAddresses();

 

                while (enumIpAddr.hasMoreElements()) {

                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();

 

                    deviceIp = inetAddress.getHostAddress().toString();

 

                    if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(deviceIp)) {

                        keepLookupOn = false;

                        break;

                    }

                }

            }

        } catch (SocketException ex) {

            ex.printStackTrace();

        }

 

        return deviceIp;

 

    }

 

你可能感兴趣的:(Android,NTLM,Authentication)