Get $_SESSION parameters via Java in Selenium Webdriver - java

I am new with Selenium Webdriver and trying to create my first test cases for application that is constructed mostly with PHP. I am creating test cases with Java.
My first test case is testing login into the system. When I run my test, browser instance is started, login information is set into login form fields and login form is submitted. After that browser dericets to used users start page as it should. So the test works as it should.
The problem is, I would like to check if the login was successful and save it in a testing report without a need for me to see the process trough in person. I figured most valid way to ensure login success is to see if PHP code have created variable $_SESSION['logged_in'] = true as it does when login process is successful. Is there any way for me to seek through $_SESSION variables with Java in my Selenium Webdriver test class?

Honestly, don't know php, but in js e.g. any js variable can be recieved using next code
driver.executeScript("return someGlobalVar");
Why you need to verify exactly value of $_SESSION variable?! I think successfull login verification can be done using other ways e.g.: a. Verify that page contains some valid information related to currently logged user (e.g. name, other fields on the page) b. Verify url c. By getting response from server (or smth like this) etc. Hope this will help.

Related

Java session variable not accessible from new page

I'm working on some old Java code with broken authentication. The web application starts with a jsp file that successfully creates and authenticates a user object. Then a session variable is created with the following code.
session.setAttribute("guiUser", userIdentity);
If I decide to get this user object within the same jsp file:
UserIdentity foo = (UserIdentity) session.getAttribute("guiUser");
System.out.println(foo.getName());
I can succesfully retrieve the authenticated user object.
However, the page is then redirected to another jsp within a different project in my workspace using
response.sendRedirect(targetPage);
When I get to this new jsp page, a login check jsp is run before anything else. The login check has the following code to instantiate a user object from the session variable(or at least this is what I think it's supposed to do.)
<jsp:useBean id="guiUser" class="com.ussposco.sso.UserIdentity" scope="session"/>
<% (code that uses guiUser object) %>
This code doesn't seem to work, because the user object is null. So I tried grabbing the user object from the session with this code.
UserIdentity foo = (UserIdentity) session.getAttribute("guiUser");
System.out.println(foo.getName());
And the object is still null.
I'm pretty new to Java web applications, but I think that this is a problem with the way that the response is redirected. I can see two different cookies in Chrome when I think there should only be one. Also, on the production website, it changes the value of a different cookie than the code I'm using(obviously out of date) uses.
As you are redirecting to the different application you will not get the same session object. Something as Single Sing On (SSO) is required for this.

How to write a Java code to read fields from a website that requires login and uses POST request?

Need some help with fetching some data from a website.
Previously , we had following code in our application and it used to fetch the required data. We just used to read the required fields by forming a URL by passing username , password and search parameter (DEA number). The same URL (with parameters ) could also be hit from browser directly to see the results. It was a simple GET request:
{URL url = new URL(
"http://www.deanumber.com/Websvc/deaWebsvc.asmx/GetQuery?UserName="+getUsername()+"&Password="+getPassword()+"&DEA="
+ deaNumber
+ "&BAC=&BASC=&ExpirationDate=&Company=&Zip=&State=&PI=&MaxRows=");
Document document = parser.parse(url.toExternalForm());
// Ask the document for a list of all <sect1> tags it contains
NodeList sections = document.getElementsByTagName("DEA");
//Followed by a loop code to get each element by using sections.item(index).getFirstChild() etc.
}
Now, the website URL has got changed to following:
https://www.deanumber.com/RelId/33637/ISvars/default/Home.htm
I am able to login to the URL with credentials , go to the search page , enter the DEA number and search. The login page comes as a pop-up once I click 'Login' link on home page. Also, the final result comes as a pop-up. This is a POST request so I am unable to form the complete URL which I could use in my code.
I am not an expert in Web Services , but I think I need a web service URL like the one mentioned in the code above. Not sure how to get that !! Even if I get the URL , I am not sure how to perform the login through Java code and search the DEA number.
Also, it would be great if I could validate the URL manually before using in Java. Let me know if there is any way.
Or, in case there is any alternate approach in Java; kindly suggest.
Thanks in advance.
First of all, the previous approach provided by the website was completely wrong and insecure, because it passes the username and password as querystring parameters in plain text. I think, they would have realized this thing and changed their way of authentication.
Also, it looks like that they have restricted the direct URL based requests from the client applications like yours. For such requests from clients, they have published the web services. Check this link. They also have mentioned the rates for web service request counts.
So, you may need to open a formal communication channel to get authentication and other details to access their web services for this purpose. Depends on what they use for web service client authentication, you may code your client to access the web services.
I hope this helps.

How to retrieve UPN(User principal Name) of current logged in user using Java

I want to retrieve UserPrincipalName of current logged in user using java.I can connect to AD and retrieve that, but i want to avoid all those configuration and other stuff, is there an easier way to get UPN using java?
UPN stored in AD is usually in userName#domainName format. If my user is john and domain is vmware, it should return john#vmware.
Please advise.
Java and JavaScript are separate languages. For a java servlet you can get the UserPrinciple name property with
GetPageContext().getRequest().getUserPrincipal().getName()
For javascript you'd need to have the server provide this via rendering it as a value, or have some framework or AJAX that allows the user principle be added to the response data or callable via the page script.

Authorize.net DPM -- perform server side processing in servlet rather than jsp

I'm currently working with a test account on Authorize.net and am utilizing their Direct Post Method form to submit transactions directly to their gateway without additional server-side processing on my end. My application is a basic jsp webapp sitting on top of Apache Tomcat 7.
Per the instructions provided on their Java Quick Start Guide I have set up 3 files to: 1) take in user input, 2) relay the response, and 3) process and display output.
Truth be told, I don't really need to display an output to the user. Instead, I would like to thoroughly process the response that Authorize.net sends me. The sample code they provide explicitly accounts for this in the relay_response.jsp file:
String receiptPageUrl = "http://MERCHANT_HOST/order_receipt.jsp";
...
net.authorize.sim.Result result = net.authorize.sim.Result.createResult(apiLoginId,
MD5HashKey, request.getParameterMap());
// perform Java server side processing...
// ...
// build receipt url buffer
StringBuffer receiptUrlBuffer = new StringBuffer(receiptPageUrl);
...
...
document.location = "<%=receiptUrlBuffer.toString()%>";
However, it looks like they want me to perform the processing in the jsp, while I would rather perform this work on the back end using a Java servlet. I've tried to accomplish this using 2 methods, neither of which work quite as I want.
Attempt 1) I replaced the 'order_receipt.jsp' tag with a url to another jsp, which subsequently submits a form to a servlet, passing all request parameters.
String receiptPageUrl = "http://<my_server's_ip_address>/another.jsp";
The problem with this approach is that in the initial forward from relay_response.jsp all of the parameters are passed via GET and appear in the URL, which I can't allow.
Attempt 2) Rather than forwarding the results to another jsp, I created a form right inside relay_response.jsp and tried to submit the form with the results passed as a request parameter.
<form id='myform' method='post' action="servlet_action" accept-charset='UTF-8'>
<input id='params' type='hidden' name='params' value='<%= paramsMap %>'/>
</form>
<script type="text/javascript">
document.getElementById("myform").submit();
</script>
The problem here is that although the browser displays my relay_response.jsp file, the value of document.location.hostname is test.authorize.net, so it doesn't recognize my action since that resides on my server rather than on authorize.net's server.
Alternatively, I have tried setting the action on the form to be the full url of my server and servlet action:
<form id='myform' method='post' action="http://<my_server's_ip_address>/webapp/servlet_action" accept-charset='UTF-8'>
But I get a warning (at least in Firefox) saying that the data is not being transmitted over a secure connection: "Although this page is encrypted, the information you have entered is to be sent over an unencrypted connection and could easily be read by a third party."
How can I pass the results of the transaction from relay_response.jsp to my Java servlet without exposing the parameters being passed to the user? Should I be using https? And why is document.location.host pointing to authorize.net rather than my relay_response.jsp?
Thanks!
A friend suggested 2 solutions for the initial question I posted, one of which I have verified.
Solution 1:
Simply redirect the initial form to servlet rather than to relay_response.jsp. Then the servlet can redirect to another jsp as apporpriate. I have verified that this works with Authorize.net DPM.
Solution 2:
Inside the scriptlet in relay_response.jsp, make a call to a Java class that actually handles the logic. You don't have to expose or write any Java code inside the scriptlet, but rather just invoke the class and call a few methods. You can pass the response parameter map as the argument to the method. I suppose the class you invoke could even be a proper servlet, though mixing these up might not be good form.

How to programmatically send a HTTP request with parameters? [duplicate]

This question already has answers here:
How to use java.net.URLConnection to fire and handle HTTP requests
(12 answers)
Closed 7 years ago.
If I use a browser to send information to the server (for example using a log-in, password page), I just fill the user text-box and the password text-box and clicking on the log-in button.
I would like to send this information but without having to use the browser. I would like to 'fill' the text-boxes but without having to do it manually in the browser. May be using a Servlet.
My question is: How to send information in text-boxes, for example, to a website, doing it from a Servlet?
why not just make a call to the URL from Java using a URL like http://your.domain.name/your/servlet/path?userFieldName=THE_VALUE_YOU_WANT_TO_PASS&passwdFieldName=PASSWORD
The servlet will feel like the values are coming from those boxes.
Or you may want to dive into Apache HTTP Client to mimick a request sent from an client.
uh..oh.. are you doing functional testing? Why not look into JMeter?
Updates as per comment
You need to know what actually form submission does? It basically forms a query string composed of Key-Values (KV) pair.
So, if you have a a text field named tfield where user has typed some text, and there is a drop down named, ddfield where user has selected optionX which has value optionX-Val. And this form gets submitted to a URL, http://my.domain.name/my/servlet -- the browser will send a request which will look like
http://my.domain.name/my/servlet?tfield=some%20text&ddfield=optionX-Val
If you want to mimic form submission, you will have to manually create a URL that has a request string containing all the fields and their values as FIELD_NAME=FIELDVALUE ordered pair separated by ampersand (&)
ah, great idea. If you use Firebug (a Firefox extension), open the NET panel in Firebug, make a manual submission of the form that you wanted to mimic. See what request is posted when you submitted the form. It will have exact URL format that you are after. Copy this URL, replace the values and make fake submissions as much as you want.
Hope this helps.
It is not clear to me what you really up to. I assume that the servlet will be the one who will send the data. Here some examples.
Using setAttribute then Forward the request
//On your servlet
request.setAttibute('user', 'admin');
request.setAttribute('password', '123');
getServletContext().getRequestDispatcher("page.jsp").forward(request, response);
//On your jsp page get the value using EL
<span>${user}</span>
Using session
//On your servlet
HttpSession session = request.getSession(true);
session.setAttribute('user', 'admin');
session.setAttribute('password', '123');
getServletContext().getRequestDispatcher("page.jsp").forward(request, response);
//On your jsp page get the value using EL
<span>${user}</span>
The above example is intended to work within the web application. To send information to another web application, which expecting a request. See sample below.
//On your jsp or servlet, you can also do the same within web application
request.sendRedirect('http://example.com?user=admin&password=123');
//on your jsp #example.com
<span>${param.user}</span>
If this is not what you mean, adding more details will be a help.
a servlet takes care of the other end: it's basically a handler for http requests that lives inside a servlet container. If I understand you correctly, you're wanting to send an http request. You can do that using command-line tools like curl, or if you want to stay within java land, you could try this example on exampledepot. Use your favourite search engine to search for more examples, e.g. with search terms such as "sending GET requests through a url".
In your situation, where you need to send information for username and password, you would need to look at the html and find the url for the form element's action attribute. Then you need to find the names of the username and password fields. Using these names as url parameters, you can construct a GET request that mimics sending a form.
NOTE: usually storing a password in plain text in code and/or sending it in plain text to a website is not a good thing to do.
Just in case anyone is interested, there is a plugin for Firefox called Tamper data. With it you can stop the sending of and http request and modify it. It will show you the "url" you need for sending the params, the values they currently have, and their name. You can check it out here. After that you can use a request.sendRedirect('url you got from Tamper Data');

Categories

Resources