Httpclient tutorial (4)

Source: Internet
Author: User
Tags http authentication rfc
Chapter iv http Authentication Httpclient provides full support for authentication modes defined by HTTP standards. The httpclient authentication framework can be expanded to support non-standard authentication modes, such as NTLM and SPNEGO. 4.1 user CREDEN

Any user authentication process requires a set of creden。 that can be used to establish a user identity. The simplest form of user creden。 can be a user name/password pair. Usernamepasswordcredentials represents a set of creden。 containing security rules and passwords. This implementation is sufficient for the Standard 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 ());

Output content:

Userpwd

ntcredentials is an implementation specified by Microsoft Windows, it contains a set of additional properties specified by Windows except the user name and password, such as the user domain name, such as in Microsoft's Windows Network, the same user can use different Authentication Settings to belong to different domains.

Ntcredentials creds = new ntcredentials ("user", "PWD", "workstation", "Domain"); system. out. println (creds. getuserprincipal (). getname (); system. out. println (creds. getPassword ());

Output content:

Domain/userpwd
4.2 Authentication mode the authscheme interface represents an abstract, challenge-oriented Authentication mode. One Authentication mode is expected to support the following features:
    • Resolves and processes the challenges of the target server in responding to requests from protected resources.
    • It provides the attributes to deal with the challenge: Authentication mode type and its parameters. If available, for example, the fields where this authentication model can be applied.
    • Generates an authentication string for the given credential group and HTTP request to respond to the real authentication challenge.
Note that the authentication mode may be stateful and involves a series of challenges-response and communication. Httpclient comes with some authscheme implementations:
    • Basic: the Basic Authentication mode is defined in RFC 2617. This Authentication mode is insecure because creden are transmitted in plain text. Although it is not secure, the Basic Authentication mode is sufficient if used in combination with TLS/SSL encryption.
    • Digest (abstract): The Digest Authentication mode is defined in RFC 2617. The Digest Authentication mode is significantly more secure than basic, and applications that do not want to use TLS/SL encryption for full transport security overheadProgramIt is also a good choice.
    • NTLM: NTLM is a proprietary Authentication mode developed by Microsoft to optimize Windows platforms. NTLM is considered to be a safer model than digest. This mode requires an external NTLM engine to work. For more details, see the ntlm_supp.txt .txt document in the httpclient.txt package.
4.3 HTTP Authentication parameters include parameters that can be used to customize the HTTP authentication process and independent authentication mode behavior:
    • 'Http. Protocol. Handle-Authentication ': Specifies whether authentication should be automatically processed. This parameter is expected to get a value of the Java. Lang. boolean type. If this parameter is not set, httpclient will automatically process authentication.
    • 'Http. Auth. credential-charset': Specifies the character set used to encode user creden. This parameter is expected to get a value of the Java. Lang. string type. If this parameter is not set, US-ASCII is used.
4.4 The Authentication Mode registry httpclient maintains an available Authentication Mode registry using the authschemeregistry class. The following modes are registered by default:
    • Basic: Basic Authentication Mode
    • Digest: Digest Authentication Mode
Note that the NTLM mode does not register each default one. The reason why NTLM cannot be enabled for each default is license and legal. For more details about how to enable NTLM support, see this section. 4.5 creden

Creden are intended to maintain a set of user creden。 and to generate user creden。 for a specific authentication range. The authentication scope includes the host name, port number, domain name, and Authentication Mode name. When using the credential provider to register creden, we can provide a wildcard (any host, any port, any domain, or any mode) to replace the determined attribute values. If direct match is not found, the creden provider is expected to be used to find the most matched range.

Httpclient can work with the physical representatives of the credentialsprovider interface. The default Implementation of credentialsprovider is called basiccredentialsprovider, which is implemented simply by using Java. util. hashmap.
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 ")));

Output content:

[Principal: U1] [Principal: U2] Null [Principal: U3]
4.6 HTTP Authentication and execution Context

Httpclient depends on the authstate class to track detailed information about the authentication process status. During HTTP request execution, httpclient creates two authstate instances: one for Target Host Authentication and the other for proxy authentication. If the target server or proxy requires user authentication, the authstate instances will be filled by the authscope, authscheme, and crednetials used during authentication. Authstate can be checked to find out the authentication type of the request, whether it matches the implementation of authscheme, and whether the creden find the user creden。 for the specified authentication range.

During HTTP request execution, httpclient adds the following Authentication-related objects to the execution context:

    • 'Http. authscheme-Registry ': The authschemeregistry instance represents the real Authentication Mode registry. The value of this attribute set in the local content takes precedence over the default value.
    • 'Http. Auth. credentials-provider': The cookiespec instance represents the real credential provider. The value of this attribute set in the local content takes precedence over the default value.
    • 'Http.auth.tar get-Process': The authstate instance represents the real target authentication status. The value of this attribute set in the local content takes precedence over the default value.
    • 'Http. Auth. Proxy-Process': The authstate instance represents the real proxy authentication status. The value of this attribute set in the local content takes precedence over the default value.

The local httpcontext object can be used to customize HTTP Authentication content and check its status before the request is executed or after the request is executed:

Httpclient = new defaulthttpclient (); httpcontext localcontext = new basichttpcontext (); httpget = new httpget ("http: // localhost: 8080 /"); httpresponse response = httpclient.exe cute (httpget, localcontext); authstate proxyauthstate = (authstate) localcontext. getattribute (clientcontext. proxy_auth_state); system. out. println ("proxy auth scope:" + proxyauthstate. getauthscope (); system. out. println ("proxy auth scheme:" + proxyauthstate. getauthscheme (); system. out. println ("proxy auth credentials:" + proxyauthstate. getcredentials (); authstate targetauthstate = (authstate) localcontext. getattribute (clientcontext. target_auth_state); system. out. println ("target auth scope:" + targetauthstate. getauthscope (); system. out. println ("target auth scheme:" + targetauthstate. getauthscheme (); system. out. println ("target auth credentials:" + targetauthstate. getcredentials ());
4.7 preemptive Authentication

Httpclient does not support out-of-the-box preemptible authentication. misuse or reuse of incorrect preemptible authentication may cause serious security problems, such as sending user creden。 in plaintext to unauthenticated third parties. Therefore, users expect to evaluate the potential benefits of preemptible authentication and content security risks in their application environments, and require the use of standard httpclient extension mechanisms such as protocol interceptors to add support for preemptible authentication.

This is a simple protocol Interceptor. If authentication is not attempted, basicscheme instances are introduced to the execution context first. Note that the interceptor must be added to the Protocol processing chain before the standard authentication interceptor.

Httprequestinterceptor preemptiveauth = new httprequestinterceptor () {public void process (final httprequest request, final httpcontext context) throws httpexception, ioexception {authstate = (authstate) context. getattribute (clientcontext. target_auth_state); credentialsprovider credsprovider = (credentialsprovider) context. getattribute (clientcontext. creds_provider); httphost targethost = (HTT Phost) context. getattribute (executioncontext. http_target_host); // If the auth mode if (authstate. getauthscheme () = NULL) {authscope = new authscope (targethost. gethostname (), targethost. getport (); // obtain credentials creds that match the target host. Credentials creds = credsprovider. getcredentials (authscope); // if any, generate basicschemeif (creds! = NULL) {authstate. setauthscheme (New basicscheme (); authstate. setcredentials (creds) ;}}}; defaulthttpclient httpclient = new defaulthttpclient (); // Add the first interceptor to httpclient in the protocol chain. addrequestinterceptor (preemptiveauth, 0 );
4.8 NTLM Certification

At present, httpclient does not support NTLM Authentication mode, and may never be supported. The reason is legal, not technical. However, NTLM authentication can use external NTLM engines such as jcifs [Signature. For details, see the ntlm_supp.txt .txt document contained in the httpclientrelease package.

4.8.1 NTLM connection persistence

The NTLM Authentication mode is expensive in terms of computing overhead, and has a great impact on the performance of Standard Basic and digest modes. This is probably one of the main reasons why Microsoft chose the NTLM Authentication mode as stateful. That is to say, once the authentication passes, the user identity is associated with the entire lifecycle of the connection. The state characteristics of NTLM connections make connection persistence very complex. For obvious reasons, persistent NTLM Connections cannot be reused by users with different user IDs. The standard Connection Manager with httpclient is capable of managing state connections. Logically related, it is also extremely important to use the same session and execution context to let them know the current user identity requests. Otherwise, httpclient will terminate the creation of a new HTTP connection for each HTTP request that protects resources based on NTLM. For more information about stateful HTTP connections, see this section.

Because NTLM connections are stateful, we recommend that you use a relatively simple method to trigger NTLM authentication, such as get or head, and reuse the same connection to execute a more costly method, in particular, they contain request entities, such as post or put.

Defaulthttpclient httpclient = new defaulthttpclient (); ntcredentials creds = new ntcredentials ("user", "PWD", "myworkstation", "Microsoft.com"); httpclient. getcredentialsprovider (). setcredentials (authscope. any, creds); httphost target = new httphost ("www.microsoft.com", 80, "HTTP "); // ensure that the same content is used to execute logic-related requests httpcontext localcontext = new basichttpcontext (); // The simple method is first executed. This will trigger NTLM authentication httpget = new httpget ("/NTLM-protected/INFO"); httpresponse response1 = httpclient.exe cute (target, httpget, localcontext); httpentity entity1 = encrypt (); if (entity1! = NULL) {entity1.consumecontent () ;}// later use the same content (and connection) to execute a high overhead method. Httppost = new httppost ("/NTLM-protected/form"); httppost. setentity (New stringentity ("lots and lots of data"); httpresponse response2 = httpclient.exe cute (target, httppost, localcontext); httpentity entity2 = response2.getentity (); If (entity2! = NULL) {entity2.consumecontent ();}

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.