how to authenticate in HTTPS by NetHTTPClient - c++

Hello
I must stress that I dont want use curl, and I must use only Embarcadero compiler. (C++Builder and Delphi)
I want send a request to a server which need authentication.
The complete command by API documentation is:
curl -X POST "https://api.demo.website.com/api/2/something" -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -d "symbol=BTC&side=buy&type=limit&timeInForce=GTC&quantity=0.1&price=4000"
Their Authentication style they provide is:
curl -u "publicKey:secretKey" https://api.demo.website.com/api/2/something
Their suggested code is: (which is not C++) :-))
import requests
session = requests.session()
session.auth = ("publicKey", "secretKey")
const fetch = require('node-fetch');
const credentials = Buffer.from('publicKey' + ':' + 'secretKey').toString('base64');
fetch('https://api.demo.website.com/api/2/something', {
method: 'GET',
headers: {
'Authorization': 'Basic ' + credentials
}
});
My Code is:
TCredentialsStorage::TCredential *MyCredential = new TCredentialsStorage::TCredential(
TAuthTargetType::Server, "", "",
UserNameEdit->Text, PasswordEdit->Text);
NetHTTPClient1->CredentialsStorage->AddCredential(*MyCredential);
StatMemo->Lines->Add(IntToStr(NetHTTPClient1->CredentialsStorage->Credentials.RefCount));
TMemoryStream *Response=new TMemoryStream;
TMemoryStream *bbkTMS =new TMemoryStream;
TNameValueArray nva;
NetHTTPRequest1->Post(URLEdit->Text, bbkTMS, Response, nva);
StatMemo->Lines->LoadFromStream(bbkTMS);
Memo1->Lines->LoadFromStream(Response);
The code is compiling but ot working... :-|
It said:
{"error":{"code":1004,"message":"Unsupported authorization method"}}
Any suggestion for me?

I find it out :-)
As I am using RAD Tool (Embarcadero) So I can use its VCL/FMX component:
THTTPBasicAuthenticator
Done!
But instead NetHTTP component group I start using RESTClient component group, much more better.

Related

Integrating Sagepay (Opayo) with Django - How to create a merchant session key

I am trying to integrate Opayo (SagePay) with Django and I am having problems generation the merchant session key (MSK).
From sagepays docs they say to use the below curl request and that I should receive the key in the response
curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=" \
-H "Content-type: application/json" \
-X POST \
-d '{
"vendorName": "sandbox"
}'
I have tried to implement this in my Django view with the following code but I receive a 422 response (Unprocessable Entity response).
import requests
def BasketView(request):
headers = {
"Authorization": "Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
"Content-type": "application/json",
}
data = {"vendorName": "sandbox"}
r = requests.post("https://pi-test.sagepay.com/api/v1/merchant-session-keys", headers=headers, params=data)
print(r)
Any ideas where I may be going wrong with this?
You are passing the wrong parameter to requests.post() you should use jsoninstead of params:
r = requests.post(
"https://pi-test.sagepay.com/api/v1/merchant-session-keys",
headers=headers,
json=data
)
By doing so, there is no need to specify the Content-Type header, it is added automatically.

Retrieving data from Streamsets Data Collector (SDC) protected by Kerberos

I am trying to retrieve data from the SDC API protected by Kerberos. Initially i am posting the credentials to the SCH login page and then using the cookies generated to access the SDC rest api. However, i am not able to post the credentials. Response code is 401 and hence not able to access api.
dpm_auth_creds = {"userName":"", "password":"" }
headers = {"Content-Type": "application/json", "X-Requested-By": "SDC"}
auth_request = requests.post("https://url:18641/sch/security/users" , data=json.dumps(dpm_auth_creds), headers=headers, verify="file.pem")
cookies = auth_request.cookies
print(auth_request.status_code)
print(auth_request.headers)
url = requests.get("https://url:18641/jobrunner/rest/v1/sdcs", cookies=cookies)
print(url.text)
Response code is 401: for auth_request.status_code
This is from the REST API page in Control Hub:
# login to Control Hub security app
curl -X POST -d '{"userName":"DPMUserID", "password": "DPMUserPassword"}' https://cloud.streamsets.com/security/public-rest/v1/authentication/login --header "Content-Type:application/json" --header "X-Requested-By:SCH" -c cookie.txt
# generate auth token from security app
sessionToken=$(cat cookie.txt | grep SSO | rev | grep -o '^\S*' | rev)
echo "Generated session token : $sessionToken"
# Call SDC REST APIs using auth token
curl -X GET https://cloud.streamsets.com/security/rest/v1/currentUser --header "Content-Type:application/json" --header "X-Requested-By:SCH" --header "X-SS-REST-CALL:true" --header "X-SS-User-Auth-Token:$sessionToken" -i
So your Python code should be more like:
dpm_auth_creds = {"userName":"", "password":"" }
headers = {"Content-Type": "application/json", "X-Requested-By": "SDC"}
auth_request = requests.post("https://url:18641/security/public-rest/v1/authentication/login" , data=json.dumps(dpm_auth_creds), headers=headers, verify="file.pem")
cookies = auth_request.cookies
print(auth_request.status_code)
print(auth_request.headers)
# Need to pass value of SS-SSO-LOGIN cookie as X-SS-User-Auth-Token header
headers = {
"Content-Type":"application/json",
"X-Requested-By":"SCH",
"X-SS-REST-CALL":"true",
"X-SS-User-Auth-Token":auth_request.cookies['SS-SSO-LOGIN']
}
url = requests.get("https://url:18641/jobrunner/rest/v1/sdcs", headers=headers)
print(url.text)

Implementing Freshsales API in Python [duplicate]

This question already has answers here:
Python request with authentication (access_token)
(8 answers)
Closed 4 years ago.
I am trying to integrate Freshsales functionality within my Django server in order to create leads, schedule appointments, etc. Freshsale's API Documentation in Python lacks detail, however. Here is a link to their API functionality using curl commands: https://www.freshsales.io/api/.
Their python code is as follows:
from .freshsales_exception import FreshsalesException
import requests
import json
def _request(path, payload):
try:
data = json.dumps(payload)
headers = { 'content-type': 'application/json', 'accept': 'application/json' }
resp = requests.post(path, data=data, headers=headers)
if resp.status_code != 200:
raise FreshsalesException("Freshsales responded with the status code of %s" % str(resp.status_code))
except requests.exceptions.RequestException as e:
raise FreshsalesException(e.message)
In the case of the curl command, for example, to create an appointment, is:
curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" -d '{"appointment":{"title":"Sample Appointment","description":"This is just a sample Appointment.","from_date":"Mon Jun 20 2016 10:30:00 GMT+0530 (IST)","end_date":"Mon Jun 20 2016 11:30:00 GMT+0530 (IST)","time_zone":"Chennai","location":"Chennai, TN, India","targetable_id":"115765","targetable_type":"Lead", "appointment_attendees_attributes":[{ "attendee_type":"FdMultitenant::User","attendee_id":"223"},{"attendee_type":"FdMultitenant::User","attendee_id":"222"},{"attendee_type":"Lead","attendee_id":"115773"}] }}' -X POST
I understand that I need to use the requests library to make a post request. However, I do not understand how I need to format the request. The furthest extent I understand to list all appointments, for example, is for my request to be the following:
my_request = "https://mydomain.freshsales.io/api/appointments/token=myexampletoken"
response = requests.post(myrequest)
I am unsure of how to create the payload to be accepted by the API to create an appointment. How might I use the requests library to accomplish this? I have searched for how to execute curl commands in Python, and the only answers I ever saw were to use the requests library. Any help is greatly appreciated!
You're missing the Authorization header. You just need to translate curl headers -H to python code. This should work, according to your syntax.
headers = {
'content-type': 'application/json',
'accept': 'application/json'
'Authorization': 'Token token=sfg999666t673t7t82'
}

posting a parameter with integer value using requests lib

I have a curl command that was given to me that I have to convert using requests.
curl --request POST "https://www.example.com" --data "user_id=200" --data "user_data=je93jfe92dj220,39fjid20djd93f302,93jfieheio02hfne,902jfoienfieshiu202" --header "Authorization: Bearer [TOKEN]"
using requests, the call should be
hdr = {'Content-Type': 'Content-type: application/json',
'Authorization': 'Bearer TOKEN' }
payload = {"user_id":200,"records":"je93jfe92dj220,39fjid20djd93f302,93jfieheio02hfne,902jfoienfieshiu202"
requests.post('https://www.example.com', headers=hdr, data=json.dumps(payload))
This isn't working as I'm getting an error returned that the 'user_id' param must be an integer. Not sure how to ensure that, as aren't all parameters formatted as strings when sent? The curl command does work, however.
Im not really sure the reason, but to make this work, just change data=json.dumps(payload) to json=json.dumps(payload). This worked just fine for me.

Django-rest-auth basic authorization error {"password":["(This field is required"]}

I i am new to django-rest-auth and apis.
Its the first time i build a rest auth and i am not very familiar with Authorization headers and Content Types.
I am trying to understand why when i try to authenticate a user in /login/ with Basic Authorization like this:
curl -X POST -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" 'https://myurl.com/rest-auth/login/' --insecure
i got this error message:
{"password":["(This field is required"]}
When passing the username and password in the body like this:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=myuser&password=mypassword' 'https://myurl.com/rest-auth/login/' --insecure
I got the key:
{"key":"b5c0f3a9c7b2fc2f58a74b25f816e2968c64712f"}
Why this is happening?
I also wonder why when trying the same in /user/ it didn't throw me any error and give me my user model serialized
curl -X GET -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" -H "Cache-Control: no-cache" 'https://myurl.com/rest-auth/user/' --insecure
The only difference i can understand is that in /login i am using POST and in /user/ is GET
Can anybody explain this to me?
Thanks for reading!
The '/auth/login/' endpoint is specifically for getting an authentication token to use with token authentication on the rest of the app. It doesn't itself support any authentication methods. The second curl command uses the correct method. the third curl command works because you are using an endpoint which does support Basic Authentication (you can could also use the token you got in the second call).
pls refer
Inet Mode Example (unprivileged user with AltAuth)
$ echo -e "GET http://localhost/slurm/v1/diag HTTP/1.1\r\nAccept: */*\r\n" |
slurmrestd -f etc/slurm.token.conf
● slurmrestd: operations_router: /slurm/v1/diag for pipe:[1052487]
● HTTP/1.1 200 OK
● Content-Length: 973
● {
● "parts_packedg": 1,
● "req_timeg": 1568051342,
● "req_time_startg": 1568050812,
● "server_thread_count": 3,
… JSON continues ...