Raghavendra
Raghavendra

Reputation: 5387

Authentication in a Servlet using Cookies raising exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /Admin.jsp at line 25

22: }
23: }
24: }
25: if(!ourcookie.getValue().equals("authval"))response.sendRedirect("Login.jsp?ref=nocookie");
26: %>

Following is the code:

<%
Cookie[] cookies=request.getCookies();
Cookie ourcookie=null;
if(cookies!=null)
{
for(int i=0;i<cookies.length;i++)
{
if(cookies[i].getName().equals("auth"))
{
ourcookie=cookies[i];
}
}
}
if(!ourcookie.getValue().equals("authval"))response.sendRedirect("Login.jsp?ref=nocookie");
%>

Upvotes: 0

Views: 453

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You don't check that ourcookie is not null before calling its getValue() method, and that probably throws a NullpointerException for non-authenticated users. Examining the logs and/or executing this code through a debugger would confirm it.

Important note: relying on the presence and value of a cookie to know if someone is authenticated is very dangerous: any script kiddie is able to send such a cookie with its requests, without the need to go through your authentication procedure. Don't rely on data coming from the client to know if a user is authenticated. Store an authenticated flag in the HTTP session, which stays at server-side.

Side note: your Java code should be indented to be much more readable, and it shouldn't be in a JSP. Scriptlets should not be used anymore. See How to avoid Java code in JSP files?.

Upvotes: 1

Related Questions