package se452examples; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.ecs.*; import org.apache.ecs.html.*; import sun.misc.BASE64Decoder; /** * A servlet to demonstrate how to handle simple client authentication * It also uses ECS to format the results. * * @version 1.0 2001/08/15 * @since 1.0 * @author Mike Gehard */ public class Authenticate extends HttpServlet{ // place to store the user/password combinations private java.util.Map users = new HashMap(); public void init(){ // add the users users.put("Mike", "se452"); users.put("Student", "hello"); } /** * Verifices the credentials of a client. If valid, access is granted. * If invalid, challenge is sent. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String auth = request.getHeader("Authorization"); if (auth != null){ // this only gets the username/password part String credent = auth.substring(6).trim(); BASE64Decoder decoder = new BASE64Decoder(); String userPass = new String(decoder.decodeBuffer(credent)); int i = userPass.indexOf(":"); String userName = userPass.substring(0,i); String password = userPass.substring(i+1); String pw = (String)users.get(userName); if (pw != null && pw.equals(password)){ authorize(response); } else { authenticate(response); } } else { authenticate(response); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // forward to doPost() doPost(request, response); } /** * Sends a challenge to the client ot authenticate the user */ private void authenticate(HttpServletResponse response){ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"JavaSecrets\""); } /** * Sends a page indicating that the authorization was a success */ private void authorize(HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Html html = new Html(); Head head = new Head(); html.addElement(head); Title title = new Title("Protected Page: Java Secrets"); head.addElement(title); Body body = new Body(); html.addElement(body); H1 h1 = new H1("Access granted. " + new Date()); body.addElement(h1); out.println(html); } }