Solved

Is it possible to sent a post request instead of a get in a servlet

Posted on 2003-11-20
10
1,141 Views
Last Modified: 2013-11-24
I'm using form-based authentication and a servlet to redirect to "j_security_check".  Is it possible to do a "post" to j_security_check, rather than a sendRedirect?

Here's my code that works (but displays password in the browser's address bar):

        StringBuffer url = new StringBuffer(100);
            url.append(request.getContextPath() + "/" + authURL);
            url.append("?j_username=" + username);
            url.append("&j_password=" + encryptedPassword);

        if (redirectString == null) {
            // signifies already correct protocol
            if (log.isDebugEnabled()) {
                log.debug("Authenticating user '" + username + "'");
            }

            response.sendRedirect(response.encodeRedirectURL(url.toString()));
        }
0
Comment
Question by:mraible
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 3

Expert Comment

by:applekanna
ID: 9791248
yes you can but u need to keep of track of sessions too...

   PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>Your page</title></head>");
    out.println("<body>");
    out.println("<form name=form1 method=post action=\"../yourURL or servelt or JSP\">");
    out.println("<input type=hidden name=j_username value="+username+">");
    out.println("<input type=hidden name=j_password value="+encrypyedPassword+">");
    out.println("<script language=\"javascript\">document.form1.submit()</script>");
    out.println("</body></html>");

Hope this helps
Cheers!
0
 
LVL 92

Expert Comment

by:objects
ID: 9792631
Just use URLConnection to send request as a POST.
0
 

Expert Comment

by:williment
ID: 9837613
If you want to simulate a HTTP POST of a form from a web you need to set the content type for the request:

       URL url = new URL(<URL you want );

       //open connection then
       HttpURLConnection connection =  (HttpURLConnection)  url.openConnection();  
       connection.setRequestMethod("POST");
       connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
     
      //write the form contents as a series of name value pairs separated by &
     //ideally this string should be URL encoded
       OutputStream outstrm = connection.getOutputStream();
       DataOutputStream cDataOutputStream = new DataOutputStream(outstrm);
       cDataOutputStream.writeBytes("FORM_FIELD1=VALUE_1&FORM_FIELD2=VALUE_2");
       cDataOutputStream.flush();
       cDataOutputStream.close();

      //read the results of your form POST
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
0
 
LVL 1

Author Comment

by:mraible
ID: 9839101
How do I get it to follow the post and display the results?  
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Expert Comment

by:williment
ID: 9841874
You can simply read the results from the post via the connection and display then out via this servlet. So the output on the browser is the result of "j_security_check"

       
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
       int n = 1;
       String line;
       while ((line = in.readLine()) != null && n <=10)
       {
           out.println(line);
           n++;
       }    
      out.close();
0
 
LVL 1

Author Comment

by:mraible
ID: 9842462
williment - I just get a blank page with nothing in it.  I think the problem is that the URLConnection probably isn't the same thing as a client connection.  The "j_security_check" is a servlet that containers (i.e. Tomcat) must implement for form-based authentication in servlets.  When using a response.sendRedirect(), the request goes back to the client and seems (to the container) the same as having <form action="j_security_check">.  I'm trying to take a form that has the action of my servlet (rather than "j_security_check") and encrypt the password, then forward to the container for authentication.  Forwarding doesn't work, posting (using the above code) doesn't work - only redirect works.  The problem is that the username and password will show up in access logs on the webserver.

More about form-based authentication at http://www.onjava.com/pub/a/onjava/2001/08/06/webform.html?page=2.
0
 
LVL 1

Author Comment

by:mraible
ID: 9843573
I got this working using Jakarta common's HttpClient.  The code is below.  Is it possible to do this with the native Java API - rather than the HttpClient?  I'll award points to whoever can help me figure that out.

            // Use HttpClient to do a Post
            HttpClient client = new HttpClient();
            client.getHostConfiguration().setHost(request.getServerName(),
                                                  request.getServerPort(),
                                                  request.getScheme());

            PostMethod authPost =
                new PostMethod(request.getContextPath() + "/" + authURL);

            // Prepare login parameters
            NameValuePair user = new NameValuePair("j_username", username);
            NameValuePair pass =
                new NameValuePair("j_password", encryptedPassword);
            authPost.setRequestBody(new NameValuePair[] { user, pass });

            client.executeMethod(authPost);

            // release any connection resources used by the method
            authPost.releaseConnection();

            // Usually a successful form-based login results in a redirect to
            // another url
            int statuscode = authPost.getStatusCode();

            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
                    (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
                    (statuscode == HttpStatus.SC_SEE_OTHER) ||
                    (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header header = authPost.getResponseHeader("location");

                if (header != null) {
                    String newuri = header.getValue();

                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }

                    GetMethod redirect = new GetMethod(newuri);

                    client.executeMethod(redirect);

                    if (newuri.indexOf("jsessionid=") > -1) {
                        String jsessionid =
                            newuri.substring(newuri.indexOf("jsessionid=") +
                                             11, newuri.length());

                        response.addHeader("Set-Cookie",
                                           "JSESSIONID=" + jsessionid +
                                           ";Path=" + request.getContextPath());
                    }

                    response.sendRedirect(newuri);
                }
            }
0
 
LVL 92

Expert Comment

by:objects
ID: 9843819
If you call setDoOutput(true); on your URLConnection it should automaticall perform a post.
Example of using POST at:
http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

0
 
LVL 1

Accepted Solution

by:
DarthMod earned 0 total points
ID: 11688315
Submitted to PAQ with points refunded (150)

DarthMod
Community Support Moderator
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now