Azure Data Factory web activity to retrieve bearer token - api

I want to invoke an api that returns bearer token (GET method). I can fetch Bearer Token successfully using .Net code. But with ADF I get only 'OK' and I see no option to fetch the Bearer Token.
Example:
ApiUrl = "https://myapi.mysite.org/api/ApiToken?user=u111&password=p111"
if status code = 'OK' then deserialize result content to fetch toekn.
Sample .Net code I used to fetch Bearer Token successfully:
var result = client.PostAsync(ApiUrl).Result;
string strRes = result.StatusCode.ToString();
if (strRes == "OK")
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);
varToken = obj.Token;
}

Use POST method in Azure data factory web activity to get the access token from an API.
Add header as content-Type: application/x-www-form-urlencoded and pass the access credentials in the body part.
You can refer to this link1 & link2 for working examples.

Related

OAuth2: Unable to Authenticate API request

Been tasked to export forms and items from Podio using the API. Trying to do this with straight Python and Requests instead of the canned API tool. Am successful at retrieving the access and refresh tokens, but am unable to make the simplest Get request. The response has the error:
"error_description":"Authentication as None is not allowed for this method"
Tried this with 2 versions of using OAuth2 in Requests, both return that response.
What is it trying to tell me? Aside from giving the token, is there any other authentication attributes required?
client = BackendApplicationClient(client_id=CLIENT_ID)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=auth_url, client_id=CLIENT_ID,
client_secret=CLIENT_SECRET)
print('token:', token)
access_token = token["access_token"]
api_url = base_url + 'user/status'
r = oauth.get(api_url)
print(r.text)
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
"Authorization": "Bearer " + token["access_token"]}
response = requests.get(api_url, headers=headers, verify=True)
print(response.text)
Here is full response:
{"error_parameters":{},"error_detail":null,"error_propagate":false,"request":{"url":"http://api.podio.com/user/status","query_string":"","method":"GET"},"error_description":"Authentication as None is not allowed for this method","error":"forbidden"}

status":401,"error":"Unauthorized","message":"","path":"/oauth/token"} /feature/HomeOuath

Feature: oauth test using
nephos-qe-sec.az.staples.com/oauth
Background:
url 'https://<<>>/oauth/token'
Scenario: oauth flow
header Content-Type = 'application/x-www-form-urlencoded'
configure ssl = true
form field grant_type = 'client_credentials'
request 'client_id=<<>>&client_secret=<<>>'
method post
status 200
def accessToken = response.access_token
Getting 401 error when running from Karate Framework.
Tried with getting the similar error.
form field client_id = '<<>>'
form field client_secret = '<<>>'
401 Snapshot

Refresh token automatically via Postman

When testing some api, the token need to be generated each 3min and I would like to do the refresh automatically, I did the following
I have a collection "CollectionGetter" which contain some requests
from "CollectionGetter" collection :
I've added the following script in "Tests" tab
var jsonData = pm.response.json();
pm.environment.set('getToken', jsonData.access_token);
on authorozation tab,set :
Type = Bearer token
Token {{getToken}}
then selected a request under CollectionGetter :
getAccount (GET url/api/account)
Auth = inherit autho from parent
and sent it
=> got a 401 JSONError: No data, empty input at 1:1
Any help ?
is my configuration correct

Can Postman Variables be Passed Into Header?

I am trying to string a few Postman requests together for testing.
In the first request I set a global variable as a test script.
tests['Status code is 200'] = (responseCode.code === 200);
if (responseCode.code === 200) {
try {
let jwt = responseBody.replace(/"/g, '');
pm.globals.set("jwt", jwt);
console.log("Variable will be set to", jwt);
}
catch(e) {
console.log(e);
}
}
In the second request I run a pre-request script as
let jwt = pm.globals.get("jwt");
Then I try to pass it into the header
Is it possible to pass a value into the header when running tests in the runner?
When running tests in the Runner the second request fails due to having an invalid jwt, and the Postman docs only show examples passing variables into the URL.
It's covered in postman auth.
Authenticate to get the JWT(oken) - Token API request
Add the test in to capture the token
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("jwt", jsonData.token);
Authorization > Type > Bearer Token
Token: {{jwt}}
Setup your Environment
Select the Environment
Select Keep variable values from the Collection Runner dialog (if you are running it in command line)
Note: I'm using version 6.3.0.

API Connect 5 - Error attempting to read the urlopen response data

I'm trying to create a REST API from a SOAP Service using IBM API Connect 5. I have followed all the steps described in this guide (https://www.ibm.com/support/knowledgecenter/en/SSFS6T/com.ibm.apic.apionprem.doc/tutorial_apionprem_expose_SOAP.html).
So, after dragging the web service block from palette, ensuring the correctness of endpoint and publishing the API, I have tried to call the API from the browser. Unfortunately, the API return the following message:
<errorResponse>
<httpCode>500</httpCode>
<httpMessage>Internal Server Error</httpMessage>
<moreInformation>Error attempting to read the urlopen response
data</moreInformation>
</errorResponse>
To testing purpose, I have logged the request and I have tried the request on SOAPUI. The service return the response correctly.
What is the problem?
In my case, the problem was in the backend charset (Content-Type: text/xml;charset=iso-8859-1).
For example, backend returns text/xml in German (or French). Api Connect cannot process character ΓΌ. It needs Content-Type: text/xml;charset=UTF-8.
I had a similar issue, in my case was the accept. if you have an Invoke and the content-type or the accept, is not matching the one of the request, or the response that you got, APIC is getting mad.
Please, check if the formats to send (contentType) and receive (accept) are the same of that your API expected. In my case the error occurs because the API returns a String and my default code is configured to receive a JSON body.
//define a JSON-PLAIN TEXT protocol
private HttpEntity<String> httpEntityWithBody(Object objToParse){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "xxx token xxx");
headers.set("Accept", MediaType.TEXT_PLAIN_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new GsonBuilder().create();
String json = gson.toJson(objToParse);
HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
return httpEntity;
}
//calling the API to APIC...
ParameterizedTypeReference<String> responseType = new
ParameterizedTypeReference<String>(){};
ResponseEntity<String> result =
rest.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.PUT, httpEntityWithBody(myDTO), responseType);
String statusCode = result.getStatusCodeValue();
String message = result.getBody();