Java SE 6 new feature: HTTP Enhancement

Source: Internet
Author: User
Tags http cookie http digest authentication idn rfc

Overview

Since its birth, Java has paid great attention to network programming applications. With the rapid development of Internet applications, Java basic libraries are constantly strengthening and expanding network-related APIs. In Java SE 6, there are many new practical features around the HTTP protocol: NTLM authentication provides a safer authentication mechanism on the window platform; JDK provides a lightweight HTTP server, a more comprehensive HTTP cookie management function, a more practical networkinterface, and international support for DNS domain names.

NTLM Authentication

Inevitably, many resources in the network are protected by security domains. To access these resources, you must authenticate the user's identity. The following is a simple example:

import java.net.*;
import java.io.*;

public class Test {
public static void main(String[] args) throws Exception {
URL url = new URL("http://PROTECTED.com");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
byte[] data = new byte[1024];
while(in.read(data)>0)
{
//do something for data
}
in.close();
}
}

When a Java program tries to read information from an authenticated website, that is, when it reads data from the inputstream that is linked to the urlconnection of the http://Protected.com, filenotfoundexception is triggered. Although I believe that the exception type is far from the cause of the actual error, this error is indeed caused by the failure of Network Authentication.

There are two ways to solve this problem:

First, set the "authentication" attribute for urlconnection:

String credit = USERNAME + ":" + PASSWORD;
String encoding = new sun.misc.BASE64Encoder().encode (credit.getBytes());
connection.setRequestProperty ("Authorization", "Basic " + encoding);

It is assumed that the http://PROTECTED.COM uses the basic (basic) authentication type.

From the above example, we can see that setting the authentication attribute is still complicated: the user must understand the details of the authentication method before giving the user name/password in a certain standard, then it is encoded in a specific encoding method. Does the Java class library provide a tool that encapsulates authentication details and only requires a user name/password?

This is another method we will introduce, using the java.net. Authentication class.

Whenever a website requires authentication, httpurlconnection will ask the authentication class for the user name and password.

The authentication class does not know which username/password the user should use. How can the user provide his/her username and password to the authentication class?

Provides a class inherited from authentication, implements the getpasswordauthentication method, and provides the user name and password in passwordauthentication:

class DefaultAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication () {
return new PasswordAuthentication ("USER", "PASSWORD".toCharArray());
}
}

Then, set it to the default (global) authentication:

Authenticator.setDefault (new DefaultAuthenticator());

What should I do if different websites require different user names and passwords?

Authentication provides sufficient information about the authentication initiator, so that the inheritance class can judge based on the information. Different authentication information is provided in the getpasswordauthentication method:

  • Getrequestinghost ()
  • Getrequestingport ()
  • Getrequestingprompt ()
  • Getrequestingprotocol ()
  • Getrequestingscheme ()
  • Getrequestingurl ()
  • Getrequestingsite ()
  • Getrequestortype ()

Another important question about authentication is the authentication type. Different authentication types require different authentication protocols. As of Java SE 6.0, authentication supports the following authentication methods:

  • HTTP Basic Authentication
  • HTTP digest Authentication
  • NTLM
  • Http spnego negotiate
    • Kerberos
    • NTLM

Here we will focus on NTLM.

NTLM is short for nt lan Manager. The early SMB protocol clearly transmitted passwords over the network, which is very insecure. Microsoft then proposed the WindowsNT challenge/response verification mechanism, that is, NTLM.

The NTLM protocol is as follows:

  1. The client first encrypts the user's password into a password hash;
  2. The client sends a user name to the server, which is directly transmitted in plaintext;
  3. The server generates a 16-bit random number and sends it to the client as a Challenge (Challenge );
  4. The client encrypts the challenge with the hash code obtained in step 1, and then returns the challenge to the server;
  5. The server sends the username, challenge to the client, and response returned by the client to the domain controller;
  6. The domain controller uses this user name to find the user's password hash in the SAM password management library, and then uses this password hash to encrypt challenge;
  7. The domain controller compares two encrypted challenge. If the same, the authentication is successful;

In versions earlier than Java 6, NTLM authentication is not supported. If you want to use httpconnection to connect to a website protected by Windows domain, you cannot pass NTLM authentication. Another method is to implement the entire Protocol process using underlying units such as socket, which is undoubtedly very complicated.

Finally, Java 6's authentication class provides NTLM support. It is very convenient to use, just like other authentication protocols:

class DefaultAuthenticator extends Authenticator {
private static String username = "username ";
private static String domain = "domain ";
private static String password = "password ";

public PasswordAuthentication getPasswordAuthentication() {
String usernamewithdomain = domain + "/ "+username;
return (new PasswordAuthentication(usernamewithdomain, password.toCharArray()));
}
}

Here, according to the naming rules of Windows domain accounts, the account name is domain name + "/" + domain username. If you do not want to add a domain name each time you generate passwordauthentication, you can set a system variable name "HTTP. Auth. NTLM. domain".

Authentication negotiation is another feature of authentication in Java 6. The current server generally provides several authentication protocols at the same time. Based on the different capabilities of the client, the server negotiates an authentication method. For example, the IIS server provides both NTLM with Kerberos and NTLM authentication methods. When the client does not support NTLM with Kerberos, NTLM authentication is performed.

Currently, the default order of authentication negotiation is:

GSS/SPNEGO -> Digest -> NTLM -> Basic

So where is the Kerberos location?

In fact, GSS/SPNEGO uses JAAS as the cornerstone, while the latter actually uses Kerberos.

Lightweight HTTP Server

Java 6 also provides the implementation of a lightweight pure Java HTTP server. The following is a simple example:

public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}

static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}

Then, access http: // localhost: 7778/MyApp/in the browser, and we get:

Figure 1 Browser display

First, httpserver is obtained from httpprovider. Here we use the implementation provided by JDK 6. You can also implement an httpprovider and the corresponding httpserver.

Httpserver has the context concept. For example, "/MyApp/" in http: // localhost: 7778/MyApp/is the Context Relative to httpserver root. Each context has an httphandler to receive HTTP requests and give answers.

Finally, an HTTP head is usually returned before httphandler gives a specific answer. Used hereHttpExchange.sendResponseHeaders(int code, int length). The Code is the return value of the HTTP response, such as the famous 404. Length refers to the length of response, in bytes.

Cookie management features

Cookie is a very common technology used in web applications to store certain user information. Although we cannot store some particularly sensitive information in cookies, cookies can still help us store some trivial information and help Web users get a better experience when accessing webpages, for example, personal search parameters, color preferences, and last access time. Network Program developers can use cookies to create stateful sessions ). Cookie applications are becoming more and more common. In Windows, we can find the cookie used by IE in the "Documents and Settings" folder. If the user name is admin, In the cookies folder of the Admin folder, we can see some files named "admin @ (domain)". The domain indicates the network domain for creating these cookie files, and some user information is stored in the file.

Scripting languages such as JavaScript have good support for cookies. . Net also has related classes to support developers to manage cookies. However, Java has never provided cookie management before Java SE 6. In Java SE 5, the java.net package contains a cookiehandler abstract class, but no specific implementation is provided. In Java SE 6, the cookie-related management class is implemented in the Java class library. With the classes supported by these cookies, Java developers can perform cookie operations in Server programming to better support http-related applications and create stateful HTTP sessions.

  • Use httpcookie to represent cookies

    The java.net. httpcookie class is a new class added in Java SE 6 to indicate HTTP cookies. Its objects can represent cookie content and support all three cookie specifications:

    • Draft Netscape
    • RFC 2109-http://www.ietf.org/rfc/rfc2109.txt
    • RFC 2965-http://www.ietf.org/rfc/rfc2965.txt

    This class stores information such as the cookie name, path, value, Protocol version number, expiration date, network domain, and maximum life cycle.

  • Use cookiepolicy to specify cookie Acceptance Policies

    The java.net. cookiepolicy interface can specify the cookie acceptance policy. The only method is used to determine whether a specific cookie can be accepted by a specific address. This class has three built-in implementation subclasses. One class accepts all cookies, the other rejects all cookies, and the other class accepts all cookies from the original address.

  • Store cookies with cookiestore

    The java.net. cookiestore interface stores and retrieves cookies. When an HTTP request is sent, it stores the accepted cookies. When an HTTP response is sent, It retrieves the corresponding cookies. In addition, when a cookie expires, it is also responsible for automatically deleting the cookie.

  • Use cookiemanger/cookiehandler to manage cookies

    Java.net. cookiemanager is the core of the entire cookie management mechanism. It is the default implementation subclass of cookiehandler. The structure of the overall HTTP cookie management mechanism is displayed:

    Figure 2. Relationship between cookie Management

    A cookiemanager contains a cookiestore and a cookiepolicy, which respectively store cookies and specify policies. You can specify both or use the default cookiemanger.

  • Example

    The following simple example illustrates the cookie-related management functions:

    // Create a default cookiemanager
    Cookiemanager manager = new cookiemanager ();

    // Get rid of rules and accept all cookies
    Manager. setcookiepolicy (cookiepolicy. accept_all );

    // Save the custom cookiemanager
    Cookiehandler. setdefault (manager );

    // Get and save the new cookie when receiving the HTTP request
    Httpcookie cookie = new httpcookie ("... (name)...", "... (value )...");
    Manager. getcookiestore (). Add (Uri, cookie );

    // When using cookies:
    // Extract cookiestore
    Cookiestore store = manager. getcookiestore ();

    // Obtain all Uris
    List <URI> Uris = store. geturis ();
    For (URI: URIs ){
    // Filter the required URI
    // Obtain all cookies belonging to this URI
    List For (httpcookie COOKIE: cookies ){
    // Retrieve the cookie
    }
    }

    // Or, retrieve all the cookies in this cookiestore.
    // Expired cookies will be automatically deleted
    List For (httpcookie COOKIE: cookies ){
    // Retrieve the cookie
    }

Other new features

Networkinterface Enhancement

From Java SE 1.4, JDK has a network tool class java.net. networkinterface, which provides some practical network functions. In Java SE 6, this tool class has been greatly enhanced and many practical methods have been added. For example:

  • public boolean isUp()

    Used to determine whether a network interface is started and running

  • public boolean isLoopback()

    Used to determine whether a network interface is a loopback interface)

  • public boolean isPointToPoint()

    Used to determine whether a network interface is a point-to-point (P2P) Network

  • public boolean supportsMulticast()

    Used to determine whether network interfaces support multicast

  • public byte[] getHardwareAddress()

    Used to obtain the hardware address (MAC)

  • public int getMTU()

    Used to obtain the maximum transmission unit (MTU, maximum transmission unit)

  • public boolean isVirtual()

    Used to determine whether a network interface is a Virtual Interface

For more information about this tool class, see the corresponding documentation in Java SE 6 (see reference resources ).

Domain Name Internationalization

In some recent RFC documents, it is required that the DNS server can parse non-ASCII encoding characters. There is an algorithm that can convert Unicode to ASCII code in this case to enable domain name internationalization. Java.net. IDN is a new class for international domain name conversion. IDN is short for "international domain name" (Internationalized Domain Names ). This class is very simple, mainly including four static functions for character conversion.

Conclusion

Java SE 6 has many new http-related features, making the Java SE platform more powerful support for network programming, especially HTTP-based Internet programming.

References

  • ReadJava SE 6 new feature seriesA complete list of articles to learn about other important enhancements of Java SE 6.

  • Java SE 6 Document: Specification document of Java SE 6, which can be found in the official description of most new features.
  • About NTLM authentication in Microsoft technet
  • RFC 2109 and RFC 2965: Two RFC

 

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.