How to set basic authorization from environment variable in postman? - postman

I want to set basic Authorization in Postman using environment variable. Because I have different authorization username and password for the different API calls.
I set my postman according to below:
In Authorization Tab: I've selected No Auth
In Header Tab: Key=Authorization Value= Basic{{MyAuthorization}}
In Body Tab:
{
"UserName": "{{UserName}}",
"ServiceUrl": "{{ServiceUrl}}"
}
//which set it from the envitonment variable
In Pre-request Tab:
// Require the crypto-js module
var CryptoJS = require("crypto-js");
// Parse the `username` and `password` environment variables
let credsParsed = CryptoJS.enc.Utf8.parse(`${pm.environment.get('admin')}:${pm.environment.get('admin')}`);
// Base64 encoded the parsed value
let credsEncoded = CryptoJS.enc.Base64.stringify(credsParsed);
// Set the valuse as an environment variable and use in the request
pm.environment.set('MyAuthorization', credsEncoded);
console.log(credsEncoded);
In Test Tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("LoginInfoID", jsonData.First.LoginInfoID);
Then I've sent the request and got unauthorized.
After that, I've set auth type to basic auth with username and password
it's working fine and I got what I wanted from the response.

Another way which worked for me:
Set up environment variables for 'username' and 'password', and save
In the Authorization tab of the request, select Basic Auth
In the Username field, enter {{username}}
For the Password field, click "Show Password", and enter {{password}}
Hope this helps others :)

You could use cryptp-js in a Pre-request Script with a very crude solution like this:
// Require the crypto-js module
var CryptoJS = require("crypto-js");
// Parse the `username` and `password` environment variables
let credsParsed = CryptoJS.enc.Utf8.parse(`${pm.environment.get('username')}:${pm.environment.get('password')}`);
// Base64 encoded the parsed value
let credsEncoded = CryptoJS.enc.Base64.stringify(credsParsed);
// Set the valuse as an environment variable and use in the request
pm.environment.set('authCreds', credsEncoded);
You could add your credentials to a set of different environment files, under the key username and password.
In the request, just set the Header like this:
You can also set those at the Collection / Sub-folder level so you're not repeating yourself in each request.
It's one way you could achieve this but there will be other ways too.

Related

How to get Facebook page feed and Filter its fields as Json using Google App script

I am trying to get a Facebook page feed through Google app script.
As of now I tried different scripts but I am getting only app token with the request and if i change it with a usertoken from graph api I got messages but no images and titles
How to get the user token and get the correct fields for as a json ,
var url = 'https://graph.facebook.com'
+ '/love.to.traavel/feed'
+ '?access_token='+ encodeURIComponent(getToken());
// + '?access_token=' + service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
Logger.log(jsondata); //check this and adjust following for loop and ht
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;
You should use a Page Token, not a User Token
You need to ask for fields you want to get, with the fields parameter: https://graph.facebook.com/love.to.traavel/feed?fields=field1,field2,...&access_token=xxx
You get a user token by authorizing your App: https://developers.facebook.com/docs/facebook-login/platforms
Be aware that extended user tokens are valid for 60 days only, so you have to refresh it once in a while. There is no user token that is valid forever. You cannot authorize through code only, it needs user interaction. The easiest way is to just generate a user token by selecting your App in the API Explorer and authorize it, like you did already. Then hardcode it in the script code.
Alternatively, you can try implementing this with the manual login flow, check out the docs for that. You can try adding the functionality using this for a custom interface where you go through the login process: https://developers.google.com/apps-script/guides/html/
Since you donĀ“t own the page, you should read this too: https://developers.facebook.com/docs/apps/review/feature/#reference-PAGES_ACCESS

Retrieve variable value from API response( in xml format) and set it to environment variable in postman

I am testing API in Postman.
I want to fetch variable from postman response which is in XML format and set
that values as the environment variable.
My postman request response is like below.
<bmi version="2.0">
<job id="2031012"></job>
</bmi>
Here BMI and JOB are tags
I want the value of ID to set an environment variable and use it for another
api test as an input parameter.
I use following code in the Test scripts
tests["Status code is 200"] = responseCode.code === 200;
tests["Body matches string"] = responseBody.has("id");
var responseJson = xml2Json(responseBody);
console.log(responseJson);
postman.setEnvironmentVariable("id",responseJson.id);{code'enter code here'}
There is a blog on the postman website showing how to do this, Extracting data from responses and chaining requests
It looks like you are mostly there and just need to retrieve the value, something along the lines of
postman.setEnvironmentVariable("id",responseJson.bmi.job.id);

Headless Chrome Puppeteer Skip Logging In To Twitter Using Cookies?

Is it possible to skip logging in to twitter by setting cookies?
I tried to copy an paste what I got from "document.cookie" in web console but that gave me the error Invalid parameters name: string value expected
await page.setCookie({
personalization_id: "v1_VDBAhQo+RMCSceKUBXfs3w==",
guest_id: "v1%3A150575165219105300",
ct0: "d9343a3b062832b6ec23a84747e518b3",
_gat: "1m",
ads_prefs: "HBERAAA=",
remember_checked_on: 1,
twid: "u=908918507005456384",
lang: "en",
tip_nightmode: true,
_ga: "GA1.2.1275876041.1505751657",
_gid: "GA1.2.1311587009.1505751657"
})
The correct syntax for setCookie is not what you used, it's:
setCookie(cookie1, cookie2, ...)
where cookie is an object containing name and value keys, like
setCookie({name: 'lang', value: 'en'})
Remember to set the cookies before loading Twitter, or to reload the page after setting them, and everything should work.
async function addCookies(cookies_str, page, domain){
let cookies = cookies_str.split(';').map(pair=>{
let name = pair.trim().slice(0,pair.trim().indexOf('='))
let value = pair.trim().slice(pair.trim().indexOf('=')+1)
return {name,value,domain}
});
await Promise.all(cookies.map((pair)=>{
return page.setCookie(pair);
}))
}
this is my way to add cookies, cookies_str was copied from browser;

Why am I getting this Authentication required error even though I am using my client id and client secret for the Foursquare API?

I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name
Let me know if you would like to see the error message. Thanks again.
I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()
#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token

Issue with Requesting OAuth Access Token

I'm working on building a library for a client to integrate with LinkedIn's API and am currently working on the OAuth implementation. I am able to request the initial token's no problem and have the user grant the authentication to my app, but when I try to request the access token with the oauth_token and oauth_verifier (along with the rest of the oauth information that I send with ever request, I get a signature invalid error.
The OAuth settings that I send are as follows:
oauth_consumer_key
oauth_nonce
oauth_timestamp
oauth_signature_method
oauth_version
oauth_token
oauth_verifier
I also add in the oauth_signature which is a signed version of all of those keys. I sign the request with the following method:
public void function signRequest(any req){
var params = Arguments.req.getAllParameters();
var secret = "#Variables.encoder.parameterEncodedFormat(getConsumer().getConsumerSecret())#&#Variables.encoder.parameterEncodedFormat(Arguments.req.getOAuthSecret())#";
var base = '';
params = Variables.encoder.encodedParameter(params, true, true);
secret = toBinary(toBase64(secret));
local.mac = createObject('java', 'javax.crypto.Mac').getInstance('HmacSHA1');
local.key = createObject('java', 'javax.crypto.spec.SecretKeySpec').init(secret, local.mac.getAlgorithm());
base = "#Arguments.req.getMethod()#&";
base = base & Variables.encoder.parameterEncodedFormat(Arguments.req.getRequestUrl());
base = "#base#&#Variables.encoder.parameterEncodedFormat(params)#";
local.mac.init(local.key);
local.mac.update(JavaCast('string', base).getBytes());
Arguments.req.addParameter('oauth_signature', toString(toBase64(mac.doFinal())), true);
}
I know that it works, because I can use the same method to request the initial token (without the oauth_token or oauth_verifier parameters), so I am assuming that it is a problem with the parameters that I am signing. (And yes I am alphabetically ordering the parameters before I sign them)
So is there a parameter that I shouldn't be including in the signature or another one that I should be?
This is an example of a base string that gets encrypted:
POST&https%3A%2F%2Fwww.linkedin.com%2Fuas%2Foauth%2FaccessToken&oauth_consumer_key%3Dwfs3ema3hi9s%26oauth_nonce%3D1887241367210%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1331326503%26oauth_token%3D8b83142a-d5a6-452e-80ef-6e75b1b0ce18%26oauth_verifier%3D94828%26oauth_version%3D1.0
When sending a POST request, you need to put the authentication information in the header, not in the query parameters.
See this page for information (look for "Sending an Authorization Header"):
https://developer.linkedin.com/documents/common-issues-oauth-authentication
I suspect this is the issue you're running into.
Okay, so it was a stupid answer, but the problem was that I didn't see the oauth_token_secret come in when the user allowed access to my app, so I was still trying to sign the request using only the consumer secret and not both the consumer secret and oauth token secret.