Unable to pass Header Authorization in JMeter. Facing unauthorizedError - jmeter

I'm running Performance test in JMeter where I have to pass Authorization details using Header Manager.
Here is my code:
String headerName = "Authorization";
String headerValue = "Basic MyKey MyValue";
Header bcHeader = new Header(headerName,headerValue);
HeaderManager hm = new HeaderManager();
hm.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
hm.add(bcHeader);
hm.add(new Header("Content-Type", "application/json"));
hm.add(new Header("Access-Control-Allow-Origin", "*"));
And I'm facing UnAuthorized error.
Please let me know if there is another way to write the code.
Thanks.

Normally you should be using HTTP Authorization Manager in order to bypass Basic HTTP Auth challenge.
However if you're going to manually construct Authorization header be aware that it should have the following form
Name: Authorization
Value: Basic
After Basic you need to provide username and password separated by colon and encoded into Base64. So if your username is MyKey and password is MyValue you should encode the string MyKey:MyValue and add the result to the header so it would look like:
Basic TXlLZXk6TXlWYWx1ZQ==
When it comes to Java code it would be something like:
String headerName = "Authorization";
String username = "MyKey";
String password = "MyValue";
Header bcHeader = new Header(headerName,
"Basic " +
Base64.encodeBase64String((username + ":" + password).getBytes(StandardCharsets.UTF_8)));
HeaderManager hm = new HeaderManager();
hm.add(bcHeader);
hm.add(new Header("Content-Type", "application/json"));
hm.add(new Header("Access-Control-Allow-Origin", "*"));
hm.setName(JMeterUtils.getResString("header_manager_title"));
hm.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
hm.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());

If you are getting authorization header value somewhere in your response you can extract and dynamic values and apply correlations to the script.
Here is what you have to do. Extract Authorization header value using regular expressions and store it in a jmeter variable lets assuem you have saved it as Auth .
Add a header manager (Right click on thread group -->config element--> Header manager) according to jmeter scoping rules.
Use ${variablename} and replace the hard coded header value with ${variablename} ,as we saved it in Auth variable you can use ${Auth}.
You can add headers to header manager click on add and give header name and value as shown below
i'm getting authorization value in request 1's reponse as shown below
so to extract this add a regular expression extractor to the same request (request 1) as shown below.
Now we can use ${Auth} in header manager , add header manager to request 2 and give header name and values as shown below
you can see in the results authorization has passed its value
For more information on Extracting variables please follow this link
Let me know if it helps

Related

Formatting violation during execution webServiceMessage.writeTo

Please help
We use WebServiceTemplate.marshalSendAndReceive, where do we pass the url, pojo, and WebServiceMessageCallback
And use interceptor where
ByteArrayTransportOutputStream byteArrayTransportOutputStream = new ByteArrayTransportOutputStream();
webServiceMessage.writeTo(byteArrayTransportOutputStream);
String request = EOL + IntegrationUtils.deleteSensitiveData(new String(byteArrayTransportOutputStream.toByteArray()));
Why before writeTo webServiceMessage is saving soapRequest in formatted form in webServiceMessage.envelope.element
But after writeTo I get message in one line without any formatting
What is problem? What does it depend on?

How to remove the characters �� from the JSON response using Jmeter?

Below is the JSON Response from the Server, How to remove the characters �� from the below Response using Jmeter
Response :
{"_id":"5d56cc5c31acfd001298e863","test_id":"5d56cc593801370012bdb2bb","display_order":"1","question_type":"MULTIPLE CHOICE","isbn":"9780393630749","status":"added","question":{"_id":"5d56cc5c31acfd001298e864","questionId":"5d4262bb56c1d800122fcb48","QuestionTitle":{"key":"","value":"","valueRTF":"","valueHtml":"��������\n
I have written the groovy Script. but it is not removing the char.
def response = prev.getResponseDataAsString();
def var1= response.replaceAll("\�", "");
and I need to use this Var1 in another request.
Most probably you're seeing these question marks due to encoding problems, try setting file.encoding property to UTF-8 in system.properties file and restart JMeter, most probably you will see normal text instead of the question marks.
If for some reason the above hint is not applicable I would recommend replacing the whole valueHtml attribute value using JsonBuilder, the relevant code would be something like:
def builder = new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()))
builder.content.question.QuestionTitle.valueHtml = ''
vars.put('Var1', builder.toPrettyString())
As the result you will have the same JSON structure with empty valueHtml attribute.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
As it is a JSON Response, add JSON Extractor Post Processor to the Parent Sampler from where the Response is expected. Extract whole JSON with following settings:
Now, use a JSR223 Sampler, with following code in script area:
String var1 = vars.get("jsonOutput");
log.info("Output: " + var1);
String replaceString=var1.replace('?','-'); // replace with whatever you want to, I am replacing it with '-'
log.info("Output: " + replaceString);
vars.put("NewString", replaceString);
Afterwards, you can use ${NewString} wherever you want.

How to encode an authorization request_uri

I need to construct a custom request_uri for an implementation of Spring OAuth2. What specific code should be used to properly encode each of the parameters in the request_uri?
The full, unencoded, request_uri is as follows, but is resulting in an error that indicates that a token is not granted:
http://localhost:9999/uaa/oauth/authorize?client_id=acme
&redirect_uri=http://localhost:8080/login&response_type=code
&state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763
As you can see, the individual parameters are:
client_id=acme
redirect_uri=http://localhost:8080/login
response_type=code
state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763
And the code that was used to construct the above request_uri is:
CsrfToken csrf = (CsrfToken) attr.getRequest().getAttribute(CsrfToken.class.getName());
String attrToken = csrf.getToken();
authorizationRequest.setState(attrToken);
String newRequestUri = "http://localhost:9999/uaa/oauth/authorize?";
String clientId = authorizationRequest.getClientId();
newRequestUri = newRequestUri + "client_id=" + clientId;
String redirectUri = authorizationRequest.getRedirectUri();
newRequestUri = newRequestUri + "&redirect_uri="+redirectUri;
Set<String> respTypes = authorizationRequest.getResponseTypes();
String respType = respTypes.iterator().next();//this plucks the first one, but is not safe for when there is a list.
newRequestUri = newRequestUri +"&response_type="+respType;
String state = authorizationRequest.getState();
newRequestUri = newRequestUri + "&state="+state;
attr.setAttribute("javax.servlet.forward.request_uri", newRequestUri, RequestAttributes.SCOPE_REQUEST);
//now re-set the request attributes to reflect the changes we just made
RequestContextHolder.setRequestAttributes(attr);
More specifically, this OP asks what syntax should be used to encode the following string values in the code above: newRequestUri, clientId, redirectUri, respType, and state.
The Official OAuth2 Spec says you can use the application/x-www-form-urlencoded Content-Type and UTF-8 encoding, but then also gives this example:
/authorize?response_type=code&client_id=s6BhdRkqt3
&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
Similarly, the Spring OAuth2 Developer Guide only contains one use of the word encode.
Seems you are looking for what is commonly called percent-encoding or URL-encoding. There are functions for this in almost every language's HTTP library, either for a single value or for a set of key-value pairs.
In practice application/x-www-form-urlencoded is almost the same as URL-encoded.

how to extract value from request in Jmeter

Hi I am passing an email which is a time function like below
email = ${__time(MMddyy)}_${__time(HMS)}#yopmail.com
The value of this function changes eveytime I call the variable email.
I would like to store this value that is generated from this function into a variable and use that in other requests.
So currently I am getting two different emails in two different http requests since there is some time lag between my two http requests.
what I would like to do is .. store the email that is being sent in first http request by extracting the value from the request and pass it in the second http request.
POST data:
email=062915_160738%40yopmail.com
I know the way to extract from html response.. but is there any way to extract from request in jmeter?
If so can someone pls tell me how to achieve this?
thank you
Add a Beanshell PostProcessor as a child of the request which sends that POST request
Put the following code into the PostProcessor's "Script" area
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
if (arg.getName().equals("email")) {
vars.put("EMAIL", arg.getValue());
break;
}
}
Refer generated value as ${EMAIL} where required.
Clarification:
above code will extract the value of email request parameter (if any) and store it to EMAIL JMeter Variable
ctx - shorthand to JMeterContext class instance
vars = shorthand to JMeterVariables class instance
Arguments and Argument - you can figure that out from JMeterContext JavaDoc
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter.
Instead of the entire email, you can store the timestamp value in a variable and then use this timestamp variable to create email anywhere you want.
This way you will can have same email every where.
Add a Beanshell PostProcessor & Add following script:
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String req_body = arg.getValue();
vars.put("req_Json",req_body);
}
here we get the output in json format:
${req_Json}=
"email":"062915_160738%40yopmail.com",
"name":"abc xyz"
Now using jp#gc Json Path Extractor extract the value of email
Json expression = $['email']
and store the value in email_value_extacted
now use the variable ${email_value_extacted} anywhere you want to use.
finally,
${email_value_extacted} = 062915_160738%40yopmail.com
Is it HTTP Sampler? If so, just put into beanshell postprocessor:
String prevQuery = prev.getQueryString(); //your request text
System.out.println(prevQuery );
Also works for any samplers:
String prevQuery = prev.getSamplerData();
You can use Regular Expression extractor to extract the e-mail address from the request URL.
Add Regular Expression Extractor as a child of sampler which sends the post request.
In the Regular Expression Extractor select URL in Response Filed to check instead of Body.
You should be able to extract e-mail id from the request in this way.

How to implement the HEAD method of httpclient

Hi I am downloading file from server. I have to take meta-information using HEAD method. andybody help me to implement the HEAD method to get "last-modified" date and modified-since date.
here is my code:
HttpClient client= new DefaultHttpClient();
//HttpGet get = new HttpGet(url);
HttpHead method = new HttpHead(url);
HttpResponse response= client.execute(method);
Header[] s=response.getAllHeaders();
System.out.println("THe header from the httpclient:");
for(int i=0; i < s.length; i++){
Header hd = s[i];
System.out.println("Header Name: "+hd.getName()
+ " " + " Header Value: " + hd.getValue());
}
//here I have to implement the HEAD method
The difference between a HEAD and a GET method is that the response will not contain a body. Otherwise, the two are the same. In other words, a HEAD method gets all the headers. It is not used for getting data of a single header, it just retrieves all headers at once.
In the code example you already have all headers, because you executed a HEAD request. In the for-loop you output all data from the headers. If the last-modified is not there, the server did not provide it for this resource.
Note that the if-modified-since is a request header field, not a response header field. You can set it to instruct the server to only return the resource if the modified-since date has passed. If you intend to only retrieve a resource when it has been modified on the server, you can just use a GET request with the if-modified-since header set. To know whether a server supports this header, check this tool: http://www.feedthebot.com/tools/if-modified/

Resources