Java example for HTTP Basic authentication (Basic authentication) __java

Source: Internet
Author: User
Tags auth base64
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.

Step two: After the browser receives the 401 unauthozied, it pops up the Logon Verification dialog box. After the user enters the user name and password,
After the browser is encoded with BASE64, it is sent to the server in the authorization header. 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, HTTPSERVLETR  
  
        Esponse 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 IOException {  
        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);     
            String user= "";     
            String password= "";
                if (decodedauth!=null) {user=decodedauth.substring (0,decodedauth.indexof (":"));     
            Password=decodedauth.substring (Decodedauth.indexof (":") +1); } if (User.equals ("Unixboy") &&password.equals ("123456")) {//authenticated successfully requ  
            Est.getsession (). setattribute ("auth", Decodedauth); RetuRN true;    
            }else{//authentication failed return false;  
        }}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 {  
        PrintWriter 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.

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.