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.
Related
I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.
The code I have for the query is as follows:
import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse
def create_checksum(http_method, raw_url, headers, request_body):
string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
return base64_string
def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
iat=time.time(), algorithm='HS256', version='V1'):
payload = {'appid': appication_id,
'iat': iat,
'version': version,
'checksum': create_checksum(http_method, raw_url, headers, request_body)}
token = jwt.encode(payload, api_key, algorithm=algorithm)
return token
# Use this region to setup the call info of the Apex Central server (server url, application id, api key)
# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'
productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''
payload = {
'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'
}
useRequestBody = json.dumps(payload)
jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
productAgentAPIPath + useQueryString,
canonicalRequestHeaders, useRequestBody, iat=time.time())
headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)
print(r.status_code)
if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
print(json.dumps(r.json(), indent=4))
else:
print(r.text)
I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post
the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2
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')
I'm trying to login to an API to retrieve an access token using a consumer secret and key. Following several threads on stackoverflow, I've gotten this far:
consumer = "<myconsumerkey>:<myconsumersecret>"
b64val = base64.b64encode(consumer.encode()).decode()
headers = {"Authorization": "Basic %s" % b64val, "Content-Type": 'application/x-www-form-urlencode'}
response = requests.post('https://mysite/token', headers=headers, verify=False)
This always throws a 415 error. I've read the requests api documentation so many times I'm going crazy where is my malfunction here?
I do not know why, but adding
data = {'grant_type': 'client_credentials'}
to the post worked. The code is:
def login():
consumer = consumer_key + ":" + consumer_secret
b64val = base64.b64encode(consumer.encode()).decode()
headers = {"Authorization": "Basic %s" % b64val}
data = {'grant_type': 'client_credentials'}
response = requests.post('https://mywebsite:8243/token', headers=headers, data=data)
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
})
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