Posted by: didiksoft | March 27, 2008

User Authentication via Sessions

We’ve already seen sessions that were created implicitly in the ShoppingCartServlet. The sessions were created as needed and only used to identify an anonymous user.

Sessions can also be used for authentication. In contrast to HTTP Basic Authentication a session can be invalidated which enables users to log out without quitting the Web Browser (which is required with Basic Authentication because there is no way to force a browser to delete the authentication credentials).

The following SessionAuthServlet shows how to do authentication with a Servlet. The doPost method processes requests to log in or out. sendPage is called by both, doGet and doPost.

 1:  import java.io.*;
 2:  import javax.servlet.*;
 3:  import javax.servlet.http.*;
 4:
 5:  public final class SessionAuthServlet extends HttpServlet
 6:  {
 7:    protected void doGet(HttpServletRequest req, HttpServletResponse res)
 8:              throws ServletException, IOException
 9:    {
10:      sendPage(req, res, req.getSession(false));
11:    }
12:
13:    protected void doPost(HttpServletRequest req, HttpServletResponse res)
14:              throws ServletException, IOException
15:    {
16:      if(req.getParameter(”login“) != null)
17:      {
18:        HttpSession session = req.getSession(true);
19:        String name = req.getParameter(”name“);
20:        if(name == null || name.length()==0) name = “Anonymous“;
21:        session.putValue(”name“, name);
22:        sendPage(req, res, session);
23:      }
24:      else
25:      {
26:        HttpSession session = req.getSession(false);
27:        if(session != null) session.invalidate();
28:        sendPage(req, res, null);
29:      }
30:    }
31:
32:    private void sendPage(HttpServletRequest req, HttpServletResponse res,
33:                          HttpSession session)
34:            throws ServletException, IOException
35:    {
36:      res.setContentType(”text/html“);
37:      res.setHeader(”pragma“, “no-cache“);
38:      PrintWriter o = res.getWriter();
39:      o.print(”<HTML><HEAD><TITLE>SessionAuthServlet</TITLE></HEAD><BODY>“);
40:      if(session == null)
41:        o.print(”<FORM METHOD=POST>Please enter your name: “+
42:<INPUT TYPE=TEXT NAME=\”name\”>“+
43:<INPUT TYPE=SUBMIT NAME=\”login\” VALUE=\”Log in\”>“+
44:</FORM></BODY></HTML>“);
45:      else
46:        o.print(”Hi ” + session.getValue(”name“) +
47:<P><FORM METHOD=POST><INPUT TYPE=SUBMIT NAME=\”logout\” “+
48:VALUE=\”Log out\”></FORM></BODY></HTML>“);
49:      o.close();
50:    }
51:  }

Leave a response

Your response:

Categories