Base64 Authentication Username and password - authentication

I have been able to write a python script to get Base 64 auth for my username and password (Admin:password) equal to --> Basic QWRtaW46cGFzc3dvcmQ=
When I add that to my header manager as:
Authorization Basic QWRtaW46cGFzc3dvcmQ=
all my HTTP Requests succeed.
in Jmeter I have googled and I find to add below in Bean PreProcessor:
import org.apache.commons.codec.binary.Base64;
String username = vars.get("Username");
String password = vars.get("Password");
String combineduserpass = username + ":" + password;
byte[] encodedUsernamePassword =
Base64.encodeBase64(combineduserpass.getBytes());
vars.put("base64HeaderValue",new String(encodedUsernamePassword));
System.out.println(encodedUsernamePassword);
but that system output gives me --> [B#558e816b which is incorrect
when I add that to my Header manager like this
Authorization Basic ${base64HeaderValue}
my HTTP Req obviously fails. The Base64 for "Admin:password should really be Basic QWRtaW46cGFzc3dvcmQ= and not [B#558e816b

You are trying to print byte array. You can print the new variable as:
System.out.println(vars.get("base64HeaderValue"));
Also your Header Manager should be under your HTTP Request so it be execute aftet script and before your request
Instead of scrpting you can use JMeter plugin of custom functions and use inside Header manager the __base64Encode function similar to:
${__base64Encode(test string, base64HeaderValue)}

To do Basic Auth, just add HTTP Authorization Manager to your plan as per this answer:
JMeter Basic Authentication
It would be configured like this if your server URL is http://localhost:8080/test:
There is no need for scripting here.

I would recommend switching to JSR223 PreProcessor and Groovy language as:
Groovy supports all modern Java language features including (but not limited to)
encoding byte arrays into Base64
decoding Base64 strings
Groovy performance is way better comparing to Beanshell
Groovy equivalent of your code would be:
vars.put('base64HeaderValue',(vars.get('Username') + ':' + vars.get('Password')).bytes.encodeBase64().toString())

Related

Authorization Header and Base64 Encoding in VimeoAPI

I am new to the world of APIs and Auth, and would certainly appreciate any help. I am attempting to authorize and receive a token through the Vimeo API (OAuth2). My question is how to properly set the value of the Authorization Header. (Table below from: https://developer.vimeo.com/api/authentication)
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
In this table is base64_encode plain text that I need to write, or does this denote a function I need to use in my language that converts x:y into Base64? M Language, in my case.
Also, are my clientID and clientSecret ready to put into the header "as-is" or do they themselves need to be converted into Base64 before being used as auth for the token endpoint?
The gist of my confusion is how exactly I should write the authorization header, because I keep getting the error "[invalid_client] A valid client ID must be provided along with any request made to Vimeo's API" when trying to POST to the token endpoint.
Thank you for any help!
The idea that you should use some sort of function to encode your clientID and secret is correct.
If you are using javascript the code might looks something like this
const clientId = 'client_id';
const clientSecret = 'client_secret';
// btoa() is a javascript built-in that base64 encodes a string
const authorizationValue = 'Basic ' + btoa( clientId + ':' + clientSecret );
You can read more about btoa() on Mozilla's documentation website.
https://developer.mozilla.org/en-US/docs/Web/API/btoa

Using Variables in Basic Authentication in an API Katalon-Studio

I have been trying to use variables for the Username and Password in the katalon-studio API, basic authentication using the following syntax:
Syntax:
GlobalVariable syntax:
However none of them are working.
please advise.
This answer might came a little bit too late, but maybe someone will find this in the future...
What the authorization tab does (and what basic authorizaton means - as mentioned in it's documentation ) is encoding the string of "${username}:${password}" by Base64.
What I did was mimic the "Update to header" button of the Authorization tab by first encoding the said string:
String basicAuthToken = "${username}:${password}".bytes.encodeBase64().toString()
Assuming authToken is a variable of the request with the type of String
Then just skip the Authorization tab and put this value straight into the header:
Name: Authorization Value: Basic ${authToken}
And now just pass the basicAuthToken as a parameter to the Webservice Request the same way you would any other variable:
WS.sendRequest(findTestObject('id_of_your_WSR_object', [('authToken'):basicAuthToken, ...any other variables]))

Encoding response value to base64 and using it on another test

I'm trying to do some testing using JMeter but I'm facing an issue trying to do some complex stuff.
I have a login HTTP request test that comes back with a response which includes an auth_token. I need to add ":" at the end and encode it to base64 to use that value on the request of another test.
I've been reading that it can be done using BeanShell but I could not achieve it yet. I will appreciate if someone could give me some steps to perform this task.
I assume you know how to get this auth_token into a JMeter Variable via i.e. Regular Expression Extractor
If you're have JMeter Plugins installed - you can use __base64Encode() function like:
${__base64Encode(${auth_token},auth_token_encoded)}
If you don't have the plugins/cannot have/don't want to have - here is how to do it with Beanshell.
Add Beanshell PostProcessor somewhere after Regular Expression Extractor (or other PostProcessor you're using to fetch the auth_token value
Put the following code into the Beanshell PostProcessor "Script" area:
import org.apache.jmeter.protocol.http.util.Base64Encoder;
String auth_token = vars.get("auth_token");
String auth_token_encoded = Base64Encoder.encode(auth_token);
vars.put("auth_token_encoded", auth_token_encoded);
See How to Use BeanShell: JMeter's Favorite Built-in Component to get started with Beanshell scripting.
Both cases assume:
you have "auth_token" value stored in ${auth_token} JMeter Variable
you will be able to access the encoded value as ${auth_token_encoded}
I had a similar test case where I need to put a file as Base64 encoded String into the body of a HTTP Request.
Instead of a BeanShell I used the groovy script functionality¹:
{
"example": "${__groovy(new File('${SCRIPT_PATH}/test.file').bytes.encodeBase64())}"
}
If you already have a String this snippet would work similar:
{
"example": "${__groovy('string to encode'.bytes.encodeBase64())}"
}
Or this is the usage with a user defined variable:
{
"example": "${__groovy('${STRING_VARIABLE}'.bytes.encodeBase64())}"
}
¹ ${SCRIPT_PATH} is a user defined variable pointing – in my case – to the folder of the loaded jmx-file: ${__BeanShell(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}

JMeter encrypted credentials

When I recorded the login process, the password is encrypted in the request, so when I tried to change the credentials by setting the password to plain text, I get 500 response code.
Try to identify the encoding mechanism and encrypt the password on the fly using Beanshell PreProcessor the following example encodes value stored under ${plainpassword} variable using Base64 encoding and stores encrypted value as ${encodedpassword} variable
import org.apache.commons.net.util.Base64;
String plainPassword = vars.get("plainpassword");
String encodedPassword = new String(Base64.encodeBase64(plainPassword.getBytes()));
vars.put("encodedpassword", encodedPassword);
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on Beanshell scripting in JMeter and a form of Beanshell cookbook.

Authenticate in Xero from Salesforce

I'm new to Oauth and I stack on getting oauth_access_token to work with Xero. Web Service authentication doesn't work for me.
Xero returns the following error message "oauth_problem=signature_invalid&oauth_problem_advice=Failed to validate signature".
The generated signature is incorrect, but what is right way to generate it?
Here is APEX code which generates Endpoint. What is wrong?
Http h = new Http();
String consumer_key='XXX';
Long tmp=(System.now().getTime()/1000);
Blob isItCorrect = Crypto.generateMac('HMacSHA1', Blob.valueOf('https://api.xero.com/api.xro/2.0'), Blob.valueOf(consumer_key));
String signature= EncodingUtil.urlEncode(EncodingUtil.base64Encode(isItCorrect), 'UTF-8');
// Try to get access token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.xero.com/oauth/RequestToken?oauth_consumer_key='+consumer_key+
'&oauth_signature_method=RSA-SHA1'+
'&oauth_signature='+signature+
'&oauth_timestamp='+tmp+ '&oauth_nonce='+tmp+'&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0');
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
System.debug('~~~ '+res.getBody());
It generates following Endpoint:
Endpoint=https://api.xero.com/oauth/RequestToken?oauth_consumer_key=ICSP7Y5K2TG7RIIC6Y7R7KLC1AHWYC&oauth_signature_method=RSA-SHA1&oauth_signature=gWP02y2EIatw4xilTvd5Iq3e0%2Fw%3D&oauth_timestamp=1372123781&oauth_nonce=1372123781&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0
Just as an aside: I've never worked with salesforce so I'm not sure if there's a better
way to leverage existing oauth work on the platform, it's very rare
now to have to write all the oauth signature stuff yourself and it's
easy to make a mistake but here goes]
I think your signature base string is incorrect.
As far as I can tell you're just performing HMAC-SHA1 over https://api.xero.com/api.xro/2.0
if you read the OAuth Spec here: http://oauth.net/core/1.0/#anchor14 you need to construct the following base string (based on the request above)
GET&https%3A%2F%2Fapi.xero.com%2Foauth%2Frequesttoken&oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce (etc etc, just append all your query parameters apart from oauth_consumer as url encoded key=value pairs, in alphabetical order)
and then you need to create the hash with the key CONSUMER_KEY&CONSUMER_SECRET (both CONSUMER_KEY and CONSUMER_SECRET should be parameter encoded as per the OAuth Spec)
That should give you a valid signature..
Edit: I found this library which might be of help: https://code.google.com/p/sfdc-oauth-playground/