Creato da pastuweb.com
Share My Page
My Social Accounts
Account FaceBook Account LinkedIn Account Twitter Account Google Plus Account Git Hub

Basic Authentication is a process where the HTTP response sent back to the http user agent contains the following info:
WWW-Authenticate BASIC realm="myRealm"
When the user agent (your browser) receives this it pops up a dialog box prompting for a username and password for "myRealm".


The user agent sends back the request with a header that looks like this:
Authorization BASIC Base64Encoded(username :password)

import java.io.*;  
import java.util.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
public class BasicAuthentication extends HttpServlet {  
 
    Hashtable validUsers = new Hashtable();  
 
    public void init(ServletConfig config) throws ServletException {  
        super.init(config);  
           
        validUsers.put("francesco:mypassword","authorized");  
    }  
    public void doGet(HttpServletRequest req, HttpServletResponse res)  
                    throws ServletException, IOException {
        doPost(req,res);
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res)  
                    throws ServletException, IOException {  
          
        res.setContentType("text/html");  
        PrintWriter out = res.getWriter();  
        
        // Get Authorization header  
        String auth = req.getHeader("Authorization");  
        // Do we allow that user?  
        if (!allowUser(auth)) {  
            // Not allowed, so report he's unauthorized  
            res.setHeader("WWW-Authenticate", "BASIC realm=\"appuntivari test\"");  
            res.sendError(res.SC_UNAUTHORIZED);  
            // Could offer to add him to the allowed user list  
        } else {  
            // Allowed, so show him the secret stuff  
            out.println("Top-secret stuff");  
        }  
    }  
    // This method checks the user information sent in the Authorization  
    // header against the database of users maintained in the users Hashtable.  
    protected boolean allowUser(String auth) throws IOException {  
          
        if (auth == null) {  
            System.out.println("No Auth");
            return false;    
        }  
        if (!auth.toUpperCase().startsWith("BASIC ")) { 
            System.out.println("Only Accept Basic Auth");
            return false;   
        }  
        
        // Get encoded user and password, comes after "BASIC "  
        String userpassEncoded = auth.substring(6);  
        // Decode it, using any base 64 decoder  
        sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();  
        String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded));  
      
        String account[] = userpassDecoded.split(":");
        System.out.println("User = "+account[0]);
        System.out.println("Pass = "+account[1]);
        
        // Check our user list to see if that user and password are "allowed"  
        if ("authorized".equals(validUsers.get(userpassDecoded))) {  
            return true;  
        } else {  
            return false;  
        }  
    }  

 

}
 
If you want test your servlet, you can download this executable JAR: RestClient 2.3
In this example I check username:password value on a element in Hashtable. But you can write a procedure to test account[] on a real database entry.
For example in Liferay Servlet doPost/doGet: 
Company company;
company = CompanyLocalServiceUtil.getCompanyByWebId("liferay.com");
....
....
String auth = request.getHeader("Authorization");  
String userNameLogin = allowUser(auth,company);
long id_user_login = UtentiLocalServiceUtil.getUtenteByUsername(userNameLogin).getId_utente();
.....
.....
.....
private String allowUser(String auth, Company company) throws IOException, PortalException, SystemException {  
        
log.info("Controllo User e Password di Login");
 
if (auth == null) { 
log.info("allowUser - no auth");
return "false";  // no auth  
}  
if (!auth.toUpperCase().startsWith("BASIC ")) {  
log.info("allowUser - no BASIC, accetto solo BASIC");
return "false";  // solo BASIC 
}  
//Recupero user e password codificati dopo "BASIC "  
String userpassEncoded = auth.substring(6);  
//Decodifico usando Base64
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();  
String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded));  
  
String[] arrayLogin = userpassDecoded.split(":");
log.info("userName "+arrayLogin[0]);
 
//Controllo user+password su Liferay
if ( UserLocalServiceUtil.authenticateForBasic(company.getCompanyId(),
CompanyConstants.AUTH_TYPE_SN , arrayLogin[0], arrayLogin[1]) != 0) {  
return arrayLogin[0];  
} else {  
return "false";  
}