Safe login inside a web page(java servlet) - servlets

I create a web page which takes user naame and if it is true, it shows some information(using servlet) otherwise it return nothing
I have a question that is this standard approach or safe.
I know that I should use a database but simplifying code I did not use and session time out doesn't matter here I will handle it.
Is this method safe.
Thanks
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName =request.getParameter("uname");
String passWord =request.getParameter("pass");
if(!userName.equals("admin"))
return;
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet fservlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Hi " +userName+ "</h3>");
out.println("</body>");
out.println("</html>");
}
}

I dont really think it is a good way to follow. Because you are sending the username and password on the request object.. so if somebody track your request, they can easily see your credentials which is a security threat. If you are concern on such requirements on your question, I would like to suggest you to use some key encryption mechanism to first encrypt it on client side before passing it to server side.
example:
http://www.jcryption.org/
http://crypto.stanford.edu/sjcl/
hope this will provide you a thought !!

Related

use of getsession() in http sessions

How come the following code snippet always enters the else block?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
if(session!=null){
String name=(String)session.getAttribute("name");
out.print("Hello, "+name+" Welcome to Profile");
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
from java doc getSession() Returns the current session associated with this request,
or if the request does not have a session, creates one.
In your code
HttpSession session=request.getSession();
It will check for current session associated with request and if there is not any,then it is going to create one.
So the check if(session!=null){ will always be true.
If you want to check that if session is present then only return HttpSession object else return null,then you can use one overloaded version of this method
HttpSession session=request.getSession(false);
See Also
JavaDoc getSession()
JavaDoc getSession(boolean)

Cannot call sendRedirect() after downloading PDF

I saw many questions like the one I am asking, but they are not exactly about what I am looking for.
I am using Command pattern, and want to create PDF-file and download it. Creating is perfect, but when I want to download it, it's starts downloading and throws an exception.
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
Here is my code from Command Pattern
#Override
public String execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException, AppException {
String fontPath = request.getServletContext().getRealPath(AppConstants.FONT_PATH);
DBManager db = DBManager.getInstance();
String ticketCode = request.getParameter("ticketCode");
String place = request.getParameter("place");
int amountTickets = Integer.valueOf(place);
String flightName = Encoding.encoding(request.getParameter("flightName"));
User user = (User) request.getSession().getAttribute("client");
String locale = (String) request.getServletContext().getAttribute("currentLocale");
db.updateFlightTickets(flightName, --amountTickets);
///////create pdf document and represent it to the byte array
ByteArrayOutputStream baos =ReportCreator.createReport(locale, fontPath, ticketCode, place, user,
db.getFlightByName(flightName));
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"Ticket\"");
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
return Path.SUCCESS;
}
Here is my "success page", sorry but can not add more, not enough reputation
<fmt:message key="success_jsp.label.success" />
And here is my servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String commandName = request.getParameter("command");
Command command = CommandContainer.get(commandName);
String forward = "";
try {
forward = command.execute(request, response);
} catch (AppException ex) {
request.setAttribute("errorMessage", ex.getMessage());
}
if (forward.equals(Path.SUCCESS)) {
response.sendRedirect(forward);
} else {
request.getRequestDispatcher(forward).forward(request, response);
}
}
Part of code in JSP, where click is calling the servlet
<td><button><fmt:message key="welcome_jsp.submit.buy_ticket" /></button></td>
How can i avoid it?
The exception says you are trying to working with the request/response once you redirect it or viceversa, and it's not valid.
Once you redirect a request, you cannot do anything else with the request/response, so getting the output stream and writing something to it is completely insane.
It's true about vice-versa situation, writing something and then redirect it will cause the browser will ignore the response data, or exception on server as I'm guessing you got.(but it depends on container)
So you either do not redirect the browser, or provide the pdf file with the target servlet/cgi where you are trying to redirect.
=================
And your current situation/problem:
Server sets the content-length, content-type,... and starts to write down some stream to the browser, since you haven't set any status, container will set default 200 OK which indicates there is some right response for the request.
Then browser will get some data(the pdf file) as 200 OK data(and consider it done), now how would you redirect the user once the response is almost done?!!?!!?!
I still do not understand why do you like to redirect a request when it's almost closed? you like to redirect the user after download complete? you cannot.

Get UsernamePasswordCredential from HttpServletRequest

I'm using Spring SimpleFormController to handle a form submission . when client sets UsernamePasswordCredentials in httpclient by httpclient.getState().setCredentials on Preemptive Authentication, how can i get this UsernamePasswordCredential in server side from HttpServletRequest inside my "onSubmit" method.
we can take the 'authorization' header value from the request and Base64-decodes the value to show that the username and password are in fact very easily readable if someone intercepts the network communication. (This is why it's a very good idea to use HTTPS for authentication).
try {
String auth = request.getHeader("Authorization");
if(auth!=null&&auth.length()>6){
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));
System.out.println(" userpassDecoded = "+userpassDecoded);
}
} catch (Exception e) {
e.printStackTrace();
}

reading from a text file in servlets

i have a login servlet from where i take a username and a password. i have a credentials.txt file where i have saved a few usernames followed by their passwords adjacently in a single line. once i read the username and password in my logincheck servlet, i want to search it in credentials.txt. if a match is found, we are directed to a welcomepage servlet, and if not found, we are again directed to the login servlet. i am getting array out of bounds exception in my code.
Plz help correct my code.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user=request.getParameter("username");
String pass=request.getParameter("password");
File obj=new File("credentials.txt");
FileReader reader=new FileReader(obj);
BufferedReader in=new BufferedReader(reader);
String aks[],temp1,temp2;
int i=0;
String line=in.readLine();
while(line!=null){
aks=line.split("\t");
while(aks[i+1]!=null){
temp1=aks[i];
temp2=aks[i+1];
if(temp1.equals(user) && temp2.equals(pass)){
RequestDispatcher obj1=request.getRequestDispatcher("welcomepage");
obj1.forward(request,response);
}
line=in.readLine();
}
}
String errormsg="username and password do not match. Please re-enter";
request.setAttribute("errormsg",errormsg);
RequestDispatcher obj1=request.getRequestDispatcher("login");
obj1.forward(request,response);
}
It looks like you're thinking that aks[i+1]!=null will evaluate to false if the element aks[i+1] doesn't exist. But if the element doesn't exist, it won't evaluate to anything; you'll always the exception you mentioned (index out of bounds). Seems like maybe what you're looking to do is actually while (aks.length>1).

How to get a form parameter in servlet? request.getAttribute does not work

Is it possible to have the same servlet perform validation? It seems that one might have to utilize some sort of recursion here, but when I type in something in the e-mail box and click submit the e-mail parameter is still blank.
After I click submit, the URL changes to: http://localhost/servlet/EmailServlet?Email=test
The page shows Email: null and the text box, but I was expecting it to go through the validation function (i.e. not be null). Is it possible to achieve this type of recursive behavior?
public class EmailServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String theForm =
"<FORM METHOD=\"GET\" ACTION=\"EmailServlet\">\n<INPUT TYPE=\"TEXT\" NAME=\"Email\"><P>\n"
+ "<INPUT TYPE=\"SUBMIT\">\n</FORM>";
String email = (String) request.getAttribute("Email");
// Bogus email validation...
if( email == null )
{
out.println("Email: " + email + "\n" + theForm);
}
else if(emailAddressNotBogous(email))
{
out.println("Thank you!");
}
else
{
out.println("“Invalid input. Please try again:\n" + theForm);
}
out.flush();
}
}
Update: as the accepted answer pointed out, there was an error in the code. Changing the getAttribute to getParameter fixes the "problem" :).
String email = (String) request.getAttributegetParameter("Email");
To get a form parameter in a servlet you use:
request.getParameter("Email");
And yes you can use the same servlet but it would be way easier to use two different servlets to do this.
you could have the form's method set to POST and then implement a doPost() method in your servlet. the doGet() will get called to display the form and the doPost() will get called to process the form submission.
alternatively you could have the doGet() method test for the presence of any parameters. if there aren't any then just display the form. if there are then process the submission...

Resources