Http Authentication Java

Source: Internet
Author: User
Tags http authentication http digest authentication md5 hash java se

Http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html

Http Authenticationoverview

The HTTP protocol handler implements a number of authentication schemes. Sun ' s implementation of Java SE Version 6 supports the following:

    • HTTP Basic Authentication (RFC2617)
    • HTTP Digest Authentication (RFC2617)
    • NTLM (defined by Microsoft)
    • Http SPNEGO Negotiate (defined by Microsoft), with the following underlying mechanisms:
      • Kerberos
      • Ntlm

Each of these schemes was described in + detail below, but they was typically used by application code in much the same The. The Java.net.Authenticator class is used to enable authentication and to provide access to a store of usernames and passwo RDS which is then used in the respective authentication schemes.

Generally, all authentication schemes work with both proxies and servers. Some (Basic and Digest) can is used simultaneously with proxies and servers. See below for what to distinguish between proxy and server authentication.

How to use the Authenticator class

Authenticator is an abstract class which was extended by applications and once installed, was invoked to obtain usernames an D passwords for authentication interactions.

Extending Java.net.Authenticator

Application code must override the getPasswordAuthentication() method. Note, the method is isn't abstract, and the default implementation does nothing. The following is a minimal example:

    Class Myauthenticator extends Authenticator {public        passwordauthentication getpasswordauthentication () {            "Password". ToCharArray ());        }    }

This is simple example returns the username "user" and a password for every HTTP authentication interaction. A More realistic example would use the other methods of java.net.Authenticator to get more information about the HTTP requ EST that needs to be authenticated. Any of the following methods is called by the implementation of Getpasswordauthentication () in order to decide Handle each request for credentials.

    • Getrequestinghost ()
    • Getrequestingport ()
    • Getrequestingprompt ()
    • Getrequestingprotocol ()
    • Getrequestingscheme ()
    • Getrequestingurl ()
    • Getrequestingsite ()
    • Getrequestortype (). Returns whether requestor is a proxy or server.
Enabling authentication

Having defined a suitable authenticator implementation class, authentication are enabled by calling

        Authenticator.setdefault (authinstance);

Where is an instance of the authinstance declared implementation class. If this isn't called, then authentication is disabled, and server authentication errors would be returned to user code via IOException objects. Once installed, the HTTP implementation would try to authenticate automatically where possible (via cached credentials, or Credentials that can is acquired from the system). If the correct credentials is not available then the user's authenticator is invoked to provide them.

Controlling which authentication scheme is used

When a-server needs a client to authenticate, it could propose a number of schemes to the client (for example Digest and NTL m) and the client may choose from among them. Normally, applications don't care which scheme was used to and the implementation automatically chooses the strongest (MOS T secure) protocol transparently.

If the user needs to ensure this a particular scheme is used and then the following system property can set to modify the Default behavior.

        -dhttp.auth.preference= "scheme"

-D is specified if the property was being set on the command line. "Http.auth.preference" is the property name, and scheme was the name of the scheme to use. If the server does not include this scheme in the IT list of proposed schemes, then the default choice is made.

Details of each authentication schemehttp Basic

Basic authentication is a simple and not very secure authentication scheme which are defined in RFC 2317. The username and password is encoded in base and is therefore easily obtainable by anyone who have access to the Packe T data. The security of basic authentication can improved when used with HTTPS, thus encrypting the request and response.

The Getrequestingprompt () method returns the Basic authentication realm as provided by the server.

Http Digest

Digest is a relatively secure scheme based on cryptographic hashes of the username and password, using the MD5 hash Algori tHM. Digest also provides the ability for the server to prove to the client that it also knows the shared secret (password). This behavior are normally disabled, because not all servers support it. This can is switched on with the following system properties:

        -dhttp.auth.digest.validateserver= "true"        -dhttp.auth.digest.validateproxy= "true"

The Getrequestingprompt () method returns the Digest authentication realm as provided by the server.

Ntlm

NTLM is a scheme defined by Microsoft. It is the more secure scheme than Basic, but less secure than Digest. NTLM can is used with proxies or servers, and not with both at the same time. If a proxy is being used, then it cannot being used for server authentication. This is because the protocol actually authenticates the TCP connection rather than the individual HTTP interactions.

On Microsoft Windows platforms, NTLM authentication attempts to acquire the user credentials from the system without Promp Ting the user ' s authenticator object. If These credentials is not accepted by the server then the user ' s authenticator would be called.

Because the Authenticator class is defined prior to NTLM being supported, it is not possible to add support in the API F Or the NTLM domain field. There is three options for specifying the domain:

    1. does not specify it. In some environments, the domain isn't actually required and the application need not specify it.
    2. The domain name can be encoded within the username by prefixing the domain name followed by a back-slash ' \ ' before the US Ername. With this method, existing applications, the Authenticator class does not need to being modified, so long as users is Made aware that this notation must be used.
    3. If a domain name is not specified as in Method 2) and the system property "Http.auth.ntlm.domain" was defined, then the Val UE of this property would be used as the domain name.
Http Negotiate (SPNEGO)

Negotiate is a scheme which potentially allows no GSS authentication mechanism to be used as a HTTP authentication Protoc Ol. Currently, the scheme is only supports Kerberos and NTLM. The NTLM have already been described above, so the section is only describes how to set up Kerberos for Http authentication.

Kerberos 5 Configuration

Since the SPNEGO mechanism would call JGSS, which in turns calls the Kerberos V5 login module to do real works. Kerberos 5 configurations is needed. which includes:

    • Some to provide Kerberos configurations. This can is achieved with the Java system property java.security.krb5.conf . For example:
            java-djava.security.krb5.conf=krb5.conf                  -djavax.security.auth.usesubjectcredsonly=false                  ClassName
    • A JAAS config file denoting what the login module to use. HTTP SPNEGO codes would look for the standard entry named com.sun.security.jgss.krb5.initiate .

For example, you can provide a file spnegoLogin.conf :

          com.sun.security.jgss.krb5.initiate {              Com.sun.security.auth.module.Krb5LoginModule                  required useticketcache=true;          };

And run Java with:

            java-djava.security.krb5.conf=krb5.conf                  -djava.security.auth.login.config=spnegologin.conf                  - Djavax.security.auth.usesubjectcredsonly=false                  ClassName
Username and Password Retrieval

Just like any other HTTP authentication scheme, the client can provide a customized java.net.Authenticator To feeds username and password to the HTTP SPNEGO module If they is needed (i.e. there) is no credential Cache available). The only authentication information needed to being checked in your Authenticator are the scheme which can be retrieved with the Code>getrequestingscheme () . The value should be "Negotiate". This means your Authenticator implementation would look like:

    Class Myauthenticator extends Authenticator {public        passwordauthentication getpasswordauthentication () {            if ( Getrequestingscheme (). Equalsignorecase ("Negotiate")) {                String krb5user;                Char[] Krb5pass;                Get Krb5user and Krb5pass in your own ...                .                Return (new Passwordauthentication (Krb5user,                            krb5pass));            } else {                ...}        }}    

Attention : According java.net.Authenticator to the specification of, it's designed to get the username and password at the SAM E time, so does not specify in the principal=xxx JAAS config file.

Scheme Preference

The client can still provide system property to http.auth.preference denote, a certain scheme should always be used as long as the SE RVer Request for it. You can use the "SPNEGO" or "Kerberos" for the system property. "SPNEGO" means you prefer to response the Negotiate scheme using the gss/spnego mechanism; "Kerberos" means prefer to response the Negotiate scheme using the Gss/kerberos mechanism. Normally, when authenticating against a Microsoft product, you can use "SPNEGO". The value "Kerberos" also works for Microsoft servers. It's only needed if you encounter a server which knows Negotiate and doesn ' t know about SPNEGO. If http.auth.preference is isn't set, the internal order Choosen is:

    • Gss/spnego-Digest, NTLM-and Basic

Noticed that Kerberos does isn't appear in the this list, since whenever Negotiate are supported, Gss/spnego is always chosen.

Fallback

If the server has provided more than one authentication schemes (including Negotiate), according to the processing order m Entioned in the last section, Java would try to challenge the Negotiate scheme. However, if the protocol cannot be established successfully (e.g. the Kerberos configuration was not correct, or the server ' s hostname is not recorded in the KDC principal DB, or the username and password provided by Authenticator are wrong), the n the 2nd strongest scheme would be automatically used. Attention : If http.auth.preference is set to SPNEGO or Kerberos and then we assume you only want to try the Negotiate scheme even If it fails. We won ' t fallback to any other scheme and your program would result in throwing an IOException saying it receives a 401 or 407 ER Ror from the HTTP response.

Example

Suppose you has an IIS server running in Windows server within an Active Directory. A Web page on the this server was configured to being protected by Integrated Windows authentication. This means the server would prompt for both Negotiate and NTLM authentication.

You need to prepare these files to get the protected file:

Code listing forRunHttpSpnego.java

Import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import    Java.net.authenticator;import Java.net.passwordauthentication;import Java.net.url;public class RunHttpSpnego { Static final String Kuser = "username"; Your account name static final String Kpass =Password; Retrieve password for your account static class Myauthenticator extends Authenticator {public passwordauthe            Ntication getpasswordauthentication () {//I haven ' t checked Getrequestingscheme () here, since for NTLM            And Negotiate, the Usrname and password is all the same.            System.err.println ("Feeding username and password for" + getrequestingscheme ());        Return (new Passwordauthentication (Kuser, Kpass.tochararray ())); }} public static void Main (string[] args) throws Exception {Authenticator.setdefault (New Myauthenticator ())        ;        URL url = new URL (args[0]);        InputStream ins = Url.openconnection (). getInputStream ();        BufferedReader reader = new BufferedReader (new InputStreamReader (INS));        String str;    while ((str = reader.readline ()) = null) System.out.println (str); }}

Code listing forkrb5.conf

[Libdefaults]    Default_realm = AD. Local[realms]    AD. LOCAL = {        KDC = kdc.ad.local    }    

Code listing forlogin.conf

com.sun.security.jgss.krb5.initiate {  Com.sun.security.auth.module.Krb5LoginModule required Donotprompt=false Useticketcache=true;};

Then, compile and RunHttpSpnego.java run:

java-djava.security.krb5.conf=krb5.conf     -djava.security.auth.login.config=login.conf     - Djavax.security.auth.usesubjectcredsonly=false     Runhttpspnego     http://www.ad.local/hello/hello.html

You'll see:

Feeding username and password for Negotiate

In the fact, if you is running on a Windows machine as a domain user, or, you is running on a Linux or Solaris machine that has already issued the kinit command and got the credential cache. The class would be MyAuthenticator completely ignored, and the output would be simply

Which shows the username and password is not consulted. This is the so-called single sign-on. Also, you can just run

Java Runhttpspnego     http://www.ad.local/hello/hello.html

To see how the fallback are done, in which case you'll see

Feeding username and password for Ntlm

Http Authentication Java

Related Article

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.