How to access secured soap endpoint in nodejs - node.js

Here is a service I need to access from nodejs:
https://test.matrikkel.no/endringsloggapi_v3/endringslogg/EndringsloggWebService?WSDL
I have the username and password.
How can I connect to service and issue requests?
Tried using 'soap' package in nodejs, but cannot understand where do I have to pass username and password.
Here is a working version done in python. Can anyone show how it works in nodejs.
import httplib, urllib
params = {}
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
"Authorization": "Basic 123"}
conn = httplib.HTTPSConnection("test.matrikkel.no")
conn.request("GET", "/endringsloggapi_v3/endringslogg/EndringsloggWebService?WSDL", params, headers)
response = conn.getresponse()
# print response.status, response.reason, response.read() to verify that call went through
conn.close()
Best Regards,
Edijs

Related

Add (AWS Signature) Authorization to python requests

I am trying to make a GET request to an endpoint which uses AWS Authorization. I made request using postman, It works. But when i tried following method in python, it's giving error.
CODE
url = 'XXX'
payload = {}
amc_api_servicename = 'sts'
t = datetime.utcnow()
headers = {
'X-Amz-Date': t.strftime('%Y%m%dT%H%M%SZ'),
'Authorization': 'AWS4-HMAC-SHA256 Credential={}/{}/{}/{}/aws4_request,SignedHeaders=host;x-amz-date,Signature=3ab1067335503c5b1792b811eeb84998f3902e5fde925ec8678e0ff99373d08b'.format(amc_api_accesskey, current_date, amc_api_region, amc_api_servicename )
}
print(url, headers)
response = requests.request("GET", url, headers=headers, data=payload)
ERROR
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.
Please point me in the right direction.
import boto3
client = boto3.client('sts')
respone=client.assume_role(RoleArn='your i am urn',RoleSessionName='PostmanNNN')

Error calling CF API login one time passcode

I am working with the CF API RESTful services. Trying to get an access token from cloud foundry's UAA API using https://login..../oauth/token web method.
I have verified that headers & body content is correct, but calling the api always returns a 400 error code with message missing grant type.
I have implemented this call in Objective-C, Swift & now Python. All tests return the same result. Here is my code example in Python:
import json
import requests
import urllib
params = {"grant_type": "password",
"passcode": "xxx"
}
url = "https://login.system.aws-usw02-pr.ice.predix.io/oauth/token"
headers = {"Authorization": "Basic Y2Y6", "Content-Type": "application/json", "Accept": "application/x-www-form-urlencoded"}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(rjson)
Each time I run this, I get the response
error invalid request, Missing grant type
Any help would be greatly appreciated.
Your code mostly worked for me, although I used a different UAA server.
I had to make only one change. You had the Accept and Content-Type headers flipped around. Accept should be application/json because that's the format you want back, and Content-Type should be application/x-www-form-urlencoded because that's the format you are sending.
See the API Docs for reference.
import json
import requests
import urllib
import getpass
UAA_SERVER = "https://login.run.pivotal.io"
print("go to {}/passcode".format(UAA_SERVER))
params = {
"grant_type": "password",
"passcode": getpass.getpass(),
}
url = "https://login.run.pivotal.io/oauth/token"
headers = {
"Authorization": "Basic Y2Y6",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(json.dumps(rjson, indent=4, sort_keys=True))
I made a couple other minor changes, but they should affect the functionality.
Use getpass.getpass() to load the passcode.
Set the target server as a variable.
Pretty print the JSON response.
The only other thing to note, is that the OAuth2 client you use must be allowed to use the password grant type. It looks like you're using the same client that the cf cli uses, so if your UAA server is part of a standard Cloud Foundry install that is likely to be true, but if it still doesn't work for you then you may need to talk with an administrator and make sure the client is set up to allow this.

Managing cookies using urllib only

This question has been asked many times but every single accepted answer utilises other librarys. I'm developing within an environment where i cannot use urllib2, http, or requests. My only option is to use urllib or write my own.
I need to send get and post requests to a server locally that requires authentication. I have no problem with the requests and this was all working until the latest security update enforced authentication. Authentication is done via cookies only.
I can send my authentication post and receive a status 200 with successful response. What i'm struggling with is pulling the cookie values out of this response and attaching them to all future post requests using urllib only.
import urllib.request, json
url = "serverurl/login"
data = {
"name" : "username",
"password" : "password"
}
jsonData = json.dumps(data).encode('utf-8')
req = urllib.request.Request(url, data=jsonData, headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req).read().decode('utf8')
print(response)
For others reference, After a few hours of trial and error and cookie research the following got a working solution.
import urllib.request, json
url = "serverurl/login"
data = {
"name" : "username",
"password" : "password"
}
jsonData = json.dumps(data).encode('utf-8')
req = urllib.request.Request(url, data=jsonData, headers={
'content-type': 'application/json'
})
response = urllib.request.urlopen(req)
cookies = response.getheader("Set-Cookie")
then in future posts you add "Cookie" : cookies to the request
req = urllib.request.Request(url, data=jsonData, headers={
"content-type" : "application/json",
"Cookie" : cookies
})

python requests getting unauthenticated or error 401

I'm trying to request post to my web server a notification but it shows error 401.
I already tested my API key in postman and it works but when I used it in python it shows error 401 or error:unathenticated.
Here's my code
import requests
req = requests.post('https://sampleweb.com/api/v1/devices/1/notifications',
json={ 'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9',
"notification": { "message":"hey", "level": 4}})
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
I've searched and read some documentations regarding to my question and I already solved it. Here's the code.
import requests
url = "https://sampleweb.com/api/v1/devices/1/notifications"
auth = {'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ',
'content-type':'application/json'}
params = {"notification":{"message":message,"level":level}}
req = requests.post(url, headers= auth, json = params)
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
The authorization needs the content-type and the params or parameters needed to be in json format. Now it works.

SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed when using requests

I am trying to send data via API but am receiving a SSL Certificate Verify Failed error with the following code:
import requests
url = "https://urlhere"
payload = "name=Test&description=Test&deadline=2017-12-31&disableEmail=true&campaignFilterId=00ad9cac28fa4c29fdb641c64b007a0b&type=Manager"
headers = {
'x-csrf-token': "TVUmiEALzVRQDkoQWbzdLI6l6NgftGoU",
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache",
'postman-token': "f8a9c488-0402-be25-aefb-cb2df65897f3"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
I am aware of using "verify=False" but understand that is not a recommended work around. What could be wrong here? I don't think it is the server since when I run this same API call in Postman it runs without issue.

Resources