Hi guys,
I'm looking to create a secure webapp using Java. It will have a very basic username/password login
which will redirect to a 'secure' area.
You can only access the pages under this secure area if you are logged in, otherwise you will be redirected
to the login JSP.
Now this is the first time I've tried this and I have collected my ideas and info from various webpages, so it is
possible i'm completely off track here.
What I've tried to do is write two small pieces of code, one is in the LoginServlet which creates a cookie, with a
name and userid (encoded). the other piece is in an 'include file' which every page under the secure area uses.
This simply looks to see if the cookie exists for that user and if it does fine, otherwise redirect to the login page.
Seems quite straight forward to me, but the problem is, if I go directly to a 'secure' apge (and there is no
cookie present) the page still opens up.
Here are the two pieces of code
LoginServlet code to create cookie:
try {
String strUserID = String.valueOf(iUserID);
Cookie cookie = new Cookie("UserID",URLEncoder.encode(strUserID));
cookie.setMaxAge(3600); // expires after 1 hour
cookie.setPath("/");
cookie.setValue(strUserID); //always update in case change of ID
response.addCookie(cookie);
} catch (Exception exC) {
System.out.println("[LoginServlet] Failed to create cookie: " +exC);
session.invalidate();
response.sendRedirect("/login.jsp");
throw new ServletException(exC.getMessage());
}
Include file code, to check cookie exists:
try {
session = request.getSession(true);
Cookie cookies[] = request.getKookies();
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("UserID")) {
strUserID=cookie.getValue();
session.putValue("stUserID",strUserID);
System.out.println("ession cookie found, user is logged in.");
} else {
response.sendRedirect("/login.jsp");
System.out.println("No session cookie for user, user must first log in.");
}
}
}
} catch (Exception ex) {
System.out.println("Error finding cookie: " +ex);
}
As i say i could be completely off track with this, but I think it should be right.