When you log on to the site, most of the time you submit the login information through a form.
But sometimes the browser will pop up a login Verification dialog box, as shown below, which is using HTTP Basic authentication.
Here's a look at the certification process:
The first step: the client sends HTTP request to the server, the server verifies that the user has logged in authenticated, if not,
The server returns a 401 unauthozied to the client and adds information to the response header "Www-authenticate".
The following figure.
The third step: the server will authorization header username password out, for verification, if the verification through, will send resources to the client according to the request.
Let's look at a sample Java code
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Sun.misc.BASE64Decoder; public class Httpauthservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse
Response) throws IOException {string sessionauth = (string) request.getsession (). getattribute ("auth");
if (Sessionauth!= null) {SYSTEM.OUT.PRINTLN ("This is next step");
NextStep (request, response);
else {if (!checkheaderauth (request, Response)) {Response.setstatus (401);
Response.setheader ("Cache-control", "No-store");
Response.setdateheader ("Expires", 0);
Response.setheader ("Www-authenticate", "Basic realm=\" test\ "); }} Private Boolean Checkheaderauth (HttpServletRequest request, httpservletresponse response) throws IO Exception {String auth = requesT.getheader ("Authorization");
SYSTEM.OUT.PRINTLN ("Auth encoded in base64 is" + getFromBASE64 (auth));
if ((auth!= null) && (Auth.length () > 6)) {auth = auth.substring (6, Auth.length ());
String Decodedauth = getFromBASE64 (auth);
System.out.println ("Auth decoded from Base64 are" + Decodedauth);
Request.getsession (). setattribute ("auth", Decodedauth);
return true;
}else{return false;
} Private String getFromBASE64 (string s) {if (s = = null) return null;
Base64decoder decoder = new Base64decoder ();
try {byte[] b = Decoder.decodebuffer (s);
return new String (b);
catch (Exception e) {return null; } public void NextStep (HttpServletRequest request, httpservletresponse response) throws IOException {Printwrit
Er pw = response.getwriter ();
Pw.println ("
When the request arrives at the server for the first time, the server does not have authenticated information and the server returns a 401 unauthozied to the client.
After the certification will be the authentication information in the session, after the session within the validity period will not be certified.
The above is a small series for everyone to bring the HTTP Basic authentication (Basic authentication) Java instance code all content, I hope that we support cloud Habitat Community ~