How to do akka http request for oauth2 access_token - akka

I am trying to request auth server to get access_token . I have a working curl command , but am unable to implement using Akka HTTP.
curl -v -u CLIENT_ID:CLIENT_SECRET -k -X POST -d {} 'URL/oauth2/token?grant_type=client_credentials&scope=Scope'
or
curl -i -H 'Authorization: Basic Base64(CLIENT_ID:CLIENT_SECRET)' --request POST URL/oauth2/token -d 'grant_type=client_credentials&scope=scope'
i am getting 405 Method Not Allowed error while requesting using http.singleRequest
def getToken(url:String, user: String, pass: String, scope:String) = {
Http()
.singleRequest(
Post(
Uri(url),
Map("grant_type" -> "client_credentials", "scope" -> s"$scope"),
).withHeaders(
Authorization(BasicHttpCredentials(user, pass)),
),
)
}

val request = HttpRequest(
HttpMethods.POST,
config.authDomain,
entity = FormData
.apply(
Map(
"grant_type" -> s"${config.grant_type}",
"scope" -> s"${config.api_scope}",
),
)
.toEntity,
).withHeaders(Authorization(BasicHttpCredentials(config.access_id, config.access_secret)))

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.

how to authenticate in HTTPS by NetHTTPClient

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.

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)

Error while generating authentication token in Django Rest Framework

I have created an endpoint localhost:8000/getauthtoken to generate the authentication token.
The curl command that i am using to get the authentication token is:
curl --request POST --url localhost:8000/getauthtoken --header 'content-type: application/json' --data '{"username":"admin", "password":"admin123"}'
But i am getting
{"password":["This field is required."],"username":["This field is required."]}
But in the command i am passing both username and password
As per the DRF documentation http://www.django-rest-framework.org/api-guide/authentication/ this is the correct way.
Use httpie (available on pypi)
Then follow this on terminal:
Http post your_ip:your_port/your_authresource/ username='' password=''
Or you can try that in Curl in right way:
curl -X POST http://localhost:8000/api-token-auth/ -d "password=aaaaa&username=user"

rest-client gem: 401 unauthorized with token

I am using the rest-client gem to try and make a post to my API.
The RestClient.post helper requires three arguments to pass headers like that: .post(url, params, headers). Have you tried something more like this?
RestClient.post('http://api.example.com/', {key: 'value'}, authorization: 'a2m...')
https://github.com/rest-client/rest-client/issues/339#issuecomment-71787018
I have followed the advice above but receive RestClient::Unauthorized - 401 Unauthorized as the response.
My code:
RestClient.post "http://api.example-dev.com:7000/v1/resources", {key: 'value'}, :authorization => 'yyyyyyyy'
I have success with the below curl command but not the above RestClient.post. Successful curl:
curl -i -X POST -d 'test[key]=1234' -H "Authorization: Token token=yyyyyyyyyyyyyy" \ http://api.example-dev.com:7000/v1/resources
This should produce the same request as curl:
`RestClient.post "http://api.example-dev.com:7000/v1/resources", {:test => {key: '1234'}}, :authorization => 'Token token=yyyyyyyyyyyyyy'`