HttpClient4.3 Tutorial Fourth HTTP Authentication

Source: Internet
Author: User
Tags http authentication httpcontext kinit

HttpClient4.3 Tutorial Fourth HTTP AuthenticationPosted on October 17, 2013


HttpClient supports both the authentication mode defined by the HTTP standard specification and some widely used non-standard authentication modes, such as NTLM and Spnego.

4.1. User credentials

Any user authentication process requires a series of credentials to determine the identity of the user. The simplest user credential can be a user name and password in this form. UsernamePasswordCredentialsThis class can be used to indicate that the credential contains the plaintext user name and password.

This class is sufficient for the authentication mode defined in the HTTP standard specification.

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pwd");    System.out.println(creds.getUserPrincipal().getName());    System.out.println(creds.getPassword());

The code above will output in the console:

    user    pwd

NTCredentialsis a credential used by Microsoft's Windows system, including username, password, and a range of other properties, such as the domain name where the user resides. In a Microsoft Windows network environment, the same user can belong to a different domain, so he has different credentials.

    NTCredentials creds = new NTCredentials("user", "pwd", "workstation", "domain");    System.out.println(creds.getUserPrincipal().getName());    System.out.println(creds.getPassword());

The above code output:

    DOMAIN/user    pwd

4.2. Certification Scheme

AutoSchemeThe interface represents an abstract challenge/response-oriented authentication scheme. A certification scheme supports the following features:

    • The client requests a protected resource from the server, the server sends over a Chanllenge (challenge), and the authentication scheme (authentication scheme) needs to parse and handle the challenge
    • Provide some property values for processed challenge: The type of authentication scheme, and some parameters required by this scheme, the scope of this scheme applies
    • Generates an authorization string using the given authorization information, and generates an HTTP request to respond to an authorization sent by the server challenge

Please note: A certification scheme may be stateful, as it may involve a range of challenges/responses.

HttpClient implements the following AutoScheme :

    • Basic: The Basic authentication scheme is defined in the RFC2617 document. This authorization scheme transmits credential information in clear text, so it is not secure. Although the Basic authentication scheme itself is unsafe, it is fully sufficient once it is used in conjunction with TLS/SSL cryptography.
    • Digest: The Digest (summary) authentication scheme is defined in the RFC2617 document. The Digest authentication scheme is much more secure than the basic scheme, and the digest solution is a good choice for those systems that cannot tolerate BASIC+TLS/SSL transmission overhead.
    • NTLM: The NTLM authentication scheme is a proprietary authentication scheme developed by Microsoft and optimized for the Windows platform. NTLM is considered more secure than digest.
    • SPNEGO: SPNEGO (Simple and Protected GSSAPI negotiation mechanism) is a "pseudo-mechanism" of GSSAPI, which is used to negotiate a true authentication mechanism. The most obvious use of spnego is in the development of Microsoft's HTTP negotiation authentication mechanism. The sub-mechanisms that can be negotiated include NTLM, Kerberos. Currently, HttpClient only supports the Kerberos mechanism. (Original: The negotiable sub-mechanisms include NTLM and Kerberos supported by Active Directory. At present HttpClient only supports the Kerberos sub-mechanism.)

4.3. Voucher Provider

Voucher providers is designed to maintain the credentials of a set of users, and providers should be able to generate such credentials when a particular credential is required. The details of the certification include hostname, port number, realm name, and authentication scheme name. When using credential provider, we can specify the hostname, port number, realm, and authentication scheme in a vague, not very precise writing. Because credential provider filters out a best-fit scenario based on what we specify.

As long as our custom credential provider implements CredentialsProvider this interface, it can be used in httpclient. The default credential, provider BasicCredentialsProvider , is called, and it uses java.util.HashMap CredentialsProvider a simple implementation of the pair.

    CredentialsProvider credsProvider = new BasicCredentialsProvider();    credsProvider.setCredentials(        new AuthScope("somehost", AuthScope.ANY_PORT),         new UsernamePasswordCredentials("u1", "p1"));    credsProvider.setCredentials(        new AuthScope("somehost", 8080),         new UsernamePasswordCredentials("u2", "p2"));    credsProvider.setCredentials(        new AuthScope("otherhost", 8080, AuthScope.ANY_REALM, "ntlm"),         new UsernamePasswordCredentials("u3", "p3"));    System.out.println(credsProvider.getCredentials(        new AuthScope("somehost", 80, "realm", "basic")));    System.out.println(credsProvider.getCredentials(        new AuthScope("somehost", 8080, "realm", "basic")));    System.out.println(credsProvider.getCredentials(        new AuthScope("otherhost", 8080, "realm", "basic")));    System.out.println(credsProvider.getCredentials(        new AuthScope("otherhost", 8080, null, "ntlm")));

The above code output:

    [principal: u1]    [principal: u2]    null    [principal: u3]

4.4.HTTP Authorization and execution context

The httpclient relies on AuthState classes to track the details of the status in the authentication process. During the HTTP request process, HttpClient creates two AuthState instances: one for the target server authentication and one for the proxy server authentication. If the server or proxy server requires user authorization information, AuthScope AutoScheme and the authentication information is populated into two AuthScope instances. Through the AutoState detection, we can determine the type of authorization requested, determine whether there is a match AuthScheme , determine whether the credential provider based on the specified authorization type successfully generated the user's authorization information.

During HTTP request execution, HttpClient adds the following authorization object to the execution context:

    • LookupObject that represents the authentication scheme used. The value of this object can be set in the local context to override the default value.
    • CredentialsProviderObject that represents the authentication scheme provider, and the value of this object can be set in the local context to override the default value.
    • AuthStateObject that represents the authentication status of the target server, and the value of this object can be set in the local context to override the default value.
    • AuthStateObject that represents the authentication status of the proxy server, and the value of this object can be set in the local context to override the default value.
    • AuthCacheObject that represents the cache of authentication data, and the value of this object can be set in the local context to override the default value.

We can customize the local HttpContext object to set the required HTTP authentication context before the request executes, or you can detect the status of HttpContext after the request is executed. To see if the authorization was successful.

    Closeablehttpclient httpclient = <...> Credentialsprovider credsprovider = <...> Lookup<authschem eprovider> authregistry = <...> Authcache Authcache = <...> Httpclientcontext context = Httpclientcon    Text.create ();    Context.setcredentialsprovider (Credsprovider);    Context.setauthschemeregistry (Authregistry);    Context.setauthcache (Authcache);    HttpGet httpget = new HttpGet ("http://www.yeetrack.com/");    Closeablehttpresponse response1 = Httpclient.execute (httpget, context);    <...> authstate proxyauthstate = Context.getproxyauthstate ();    System.out.println ("Proxy auth State:" + proxyauthstate.getstate ());    System.out.println ("Proxy auth scheme:" + proxyauthstate.getauthscheme ());    System.out.println ("Proxy auth Credentials:" + proxyauthstate.getcredentials ());    Authstate targetauthstate = Context.gettargetauthstate ();    System.out.println ("Target auth State:" + targetauthstate.getstate ()); System.out.println ("Target Auth Scheme: "+ targetauthstate.getauthscheme ()); System.out.println ("Target auth Credentials:" + targetauthstate.getcredentials ());

4.5. Cache Authentication Data

Starting with version 4.1, HttpClient automatically caches the authentication information passed by the validation. But in order to use this cached authentication information, we must execute the logic-related request in the same context. Once the scope of the context is exceeded, the cached authentication information is invalidated.

4.6. Preemptive authentication

HttpClient default does not support preemptive authentication, because once the preemptive authentication is misused or wrong, it can lead to a series of security problems, such as the user's authentication information is sent to unauthorized third-party servers in clear text. As a result, users are required to evaluate the benefits and risks associated with preemptive authentication based on their application's specific environment.

Even so, HttpClient allows us to enable preemptive authentication through configuration by populating the authentication information cache into context in advance, so that the method executed in this context uses preemptive authentication.

    Closeablehttpclient httpclient = <...> httphost targethost = new Httphost ("localhost", "http");    Credentialsprovider Credsprovider = new Basiccredentialsprovider (); Credsprovider.setcredentials (New Authscope (Targethost.gethostname (), Targethost.getport ()), new use    Rnamepasswordcredentials ("username", "password"));    Create Authcache object Authcache Authcache = new Basicauthcache ();    Create the Basicscheme and add it to the auth cache basicscheme BasicAuth = new Basicscheme ();    Authcache.put (Targethost, BasicAuth);    Add Autocache to context httpclientcontext context = httpclientcontext.create ();    Context.setcredentialsprovider (Credsprovider);    HttpGet httpget = new HttpGet ("/"); for (int i = 0; i < 3; i++) {Closeablehttpresponse response = Httpclient.execute (Targethost, HT        Tpget, context);        try {httpentity entity = response.getentity ();        } finally {response.close (); }    }

4.7. NTLM Authentication

Starting with version 4.1, HttpClient has fully supported NTLMV1, NTLMV2, and NTLM2 certifications. When people we can still use external NTLM engines (such as the JCIFS Library developed by Samba) as part of the Windows Interoperability program.

4.7.1. NTLM connection Persistence

Compared Basic to Digest authentication, NTLM authentication requires more computational overhead, and has a greater performance impact. This may also be one of the main reasons Microsoft has designed the NTLM protocol as a stateful connection. In other words, once an NTLM connection is established, the user's identity is associated with it throughout its lifecycle. The status of NTLM connections makes connection persistence more complex, the stateful nature of NTLM connections makes connection persistence more complex, as for the Obviou s reason persistent NTLM connections May is re-used by users with a different user identity. The standard Connection manager in HttpClient can manage stateful connections. However, logically related requests in the same session must use the same execution context in order to use the user's identity information. Otherwise, httpclient ends the old connection, creating a new HTTP connection for each HTTP request, in order to obtain the resources protected by the NTLM protocol. To update the information about the HTTP status connection, click here.

Because the NTLM connection is stateful, it is generally recommended to use a more lightweight approach to punish NTLM authentication (such as method), and then use this established connection to perform a relative heavyweight approach, especially if the request for an attachment request entity (such as a post, put request) is used.

    Closeablehttpclient httpclient = <...> Credentialsprovider credsprovider = new Basiccredentialsprovider (); Credsprovider.setcredentials (Authscope.any, New Ntcredentials ("User", "pwd", "MyWorkstation", "microsoft.com"    ));    Httphost target = new Httphost ("www.microsoft.com", "http");    Use the same context to perform logic-related requests Httpclientcontext context = Httpclientcontext.create ();    Context.setcredentialsprovider (Credsprovider);    Use a lightweight request to trigger NTLM authentication HttpGet HttpGet = new HttpGet ("/ntlm-protected/info");    Closeablehttpresponse response1 = Httpclient.execute (target, httpget, context);    try {httpentity entity1 = response1.getentity ();    } finally {response1.close ();    }//Using the same context, perform a heavyweight method httppost HttpPost = new HttpPost ("/ntlm-protected/form");    Httppost.setentity (New stringentity ("lots and lots of data");    Closeablehttpresponse Response2 = Httpclient.execute (target, httppost, context); try {httpentity Entity2 = response2.gEtentity ();    } finally {response2.close (); }

4.8. Spnego/kerberos Certification

SPNEGO (Simple and Protected GSSAPI megotiation mechanism), the SP authentication protocol can be used when both parties do not know what protocol the other party can use/provide. This protocol is often used in Kerberos authentication schemes. It can wrap other mechanisms, however the current version in HttpClient are designed solely with Kerberos in mind.

4.8.1. Using Spnego in Httpcient

The SPNEGO Certification Scheme is compatible with Sun Java 1.5 and later. However, it is highly recommended to jdk1.6 above. The classes provided by Sun's JRE are almost entirely capable of handling Kerberos and Spnego tokens. This means that a lot of the GSS classes need to be set up. SpnegoSchemeis a very simple class that can be used to handle marshalling the tokens and read and write the correct header message.

The best way to get started is to find the file from the sample program KerberosHttpClient.java and try to get it running. There may be a lot of problems with the running process, but it may be a little smoother if you have a higher personality. This file will provide some output to help us Debug.

In Windows systems, the user's login credentials should be used by default, and of course we can use it kinit to overwrite the credential, for example $JAVA_HOME\bin\kinit [email protected] , which is useful when testing and debugging. If you want to use the default login credentials of Windows back, delete the cache file created by Kinit.

Make sure that it is listed in the krb5.conf file domain_realms . This can solve a lot of unnecessary problems.

4.8.2. Using Gss/java KERBEROS

The following document is for Windows systems, but much of the information is also appropriate for UNIX.

org.ietf.jgssThis class has a number of configuration parameters, most of which are krb5.conf/krb5.ini configured in the file. For more information, see here.

login.conf file

The following is a basic login.conf file that enables IIS and JBoss negotiation modules for the Windows platform.

The system configuration file java.security.auth.login.config can specify login.conf the path to the file.
login.confMay look something like this:

    com.sun.security.jgss.login {      com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;    };    com.sun.security.jgss.initiate {      com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;    };    com.sun.security.jgss.accept {      com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;    };

4.8.4. KRB5. Conf/krb5. INI file

If not specified manually, the system uses the default configuration. If you want to specify manually, you can java.security.krb5.conf set the system variable in the specified krb5.conf path. krb5.confthe content might look like this:

    [libdefaults]        default_realm = AD.EXAMPLE.NET        udp_preference_limit = 1    [realms]        AD.EXAMPLE.NET = {            kdc = KDC.AD.EXAMPLE.NET        }    [domain_realms]    .ad.example.net=AD.EXAMPLE.NET    ad.example.net=AD.EXAMPLE.NET

4.8.5. Detailed configuration of Windows

In order to enable Windows to use the current user's tickets, javax.security.auth.useSubjectCredsOnly this system variable should be set to false , and need to add this entry in the Windows registry allowtgtsessionkey , and allow session keys to be sent in the Kerberos ticket-granting Ticket.

Windows Server 2003 and Windows SP4 are configured as follows:

    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters    Value Name: allowtgtsessionkey    Value Type: REG_DWORD    Value: 0x01

The Windows XP SP2 configuration is as follows:

    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos    Value Name: allowtgtsessionkey    Value Type: REG_DWORD    Value: 0x01

easy to trace: A little progress every day

Reprint please keep the link address: http://www.yeetrack.com/?p=825

HttpClient4.3 Tutorial Fourth HTTP Authentication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.