I'm creating an app that has to show data of an active directory (which is hosted in microsoft azure) i have been told, that this request of data is going to be accomplished by using the Microsoft Graph API through HTTP GET requests.
Apart from “checking” the active directory data in azure, my app has to be capable of read the local accounts’ permissions, so to acomplish that this wouldn’t be possible to be read from the active directory, which means that I will have to check in the computers itself. For that problem, I've been told that I have to do it through powershell programming (to retrieve data of the local accounts).
At the end my application has to run on AWS Lambda.
More than code i would like guys if you can give me an approach of what to use to get to the solution.
What I have done so far:
I created a python file with this code to connect to the microsoft graph API:
There I added a token to access to the graph API, but i couldn't succeed.
I obtained the token from here, that is supposed to be a sample token of microsoft. For now instead of running my app on AWS Lambda, im running it on pycharm.
My Code on python to access to Azure Active Directory:
import http.client, urllib.request, urllib.parse, urllib.error, base64
# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
params = urllib.parse.urlencode({
# Specify values for the following required parameters
'api-version': '1.6'})
try:
conn = http.client.HTTPSConnection('graph.windows.net')
# Specify values for path parameters (shown as {...}) and request body if needed
conn.request("GET", "/myorganization/groups/f795caea-121d-49c7-8ae6-a95623add8aa?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
This is the error I get after executing my code:
C:\Users\Joan\PycharmProjects\Prueba\venv\Scripts\python.exe C:/Users/Joan/PycharmProjects/Prueba/GraphTest.py
b'{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2018-07-02T21:01:26","requestId":"c3429e83-9cee-4f79-bfa5-642aa8da482a","values":null}}'
Process finished with exit code 0
This section:
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
Requests an additional space between 'Bearer' and the token itself:
headers = {
'Authorization': 'Bearer ' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
I'm assuming this is just some scratch POC code but, just in case, keep in mind that your token will expire after 1hr so hardcoding it like this doesn't make sense. You'll want to fetch a new token as needed and inject it into the header when making the call.
Related
When I run this python script on my PC I get the following error: An error occurred: 404
I have created a Wix Store. (Free plan).
While logged into the Wix Store, I have created API.
Account Settings -> API (https://manage.wix.com/account/api-keys)
From the account settings I have the Account ID, and the API Key, with permissions to read, write, delete, update store items.
I have also gone to https://dev.wix.com/ and created an app there.
This created APP provides OAUTH App ID & App Secret Key.
import requests
# Replace YOUR_APP_SECRET and YOUR_STORE_ID with your actual values
# Not sure which set of credentials to put here, since none worked.
app_secret = 'see_post'
store_id = 'see_post'
headers = {
'accept': 'application/json',
'x-wix-app-secret': app_secret
}
response = requests.get(f'https://api.wix.com/stores/{store_id}/products', headers=headers)
if response.status_code == 200:
products = response.json()
print(products)
else:
print('An error occurred:', response.status_code)
Things that confuse me:
Do I need a Wix Developer account, and then create an APP, and install this app on my wix store. (I have already done this, just created an app, named it, nothing else, and installed it, hoping that I could use the app secret key, and my stores site ID, to retrieve the store products.)
Do I use the APP ID & APP Secret Key in my script? Or do I use the Account ID and Account API that I created in the account of the Wix Store.
Is the store id in the URL of the wix dashboard?
https://manage.wix.com/dashboard/23861c7e-333-333-3333-4a18d5f55da2/
What I wish to accomplish, figure out how to make this script run correctly.
Then I will modify it to do the following:
List
Add/remove products
Change Product attributes such as price, description, etc.
Sync Inventory between Wix, and a local database.
Update 1:
I'm now using this code as provided in the API docs.
import json
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'token generated by https://dev.wix.com/api/rest/wix-stores/inventory/query-inventory'
}
data = {
"query": {},
"options": {}
}
response = requests.post('https://www.wixapis.com/stores/v2/inventoryItems/query', headers=headers, data=json.dumps(data))
if response.status_code == 200:
inventory_items = response.json()
print(inventory_items)
else:
print('An error occurred:', response.status_code)
However the auth token is only valid for 10 minutes.
a. How can I regenerate this token from my python script?
b. Do I have to use these temp. tokens? Can't I just use the API key?
Looks to me like you're going about this the hard way. I think a much easier approach would be to use http-functions to expose several endpoints that then use the wix-stores-backend API and the wix-data API to access your product data.
I am trying to make a request to the Proactive Events API by using the requests module of Python.
However I always receive a response that the scope is invalid.
Can anyone help? What am I doing wrong? My code looks like this:
#ask.launch
def launch():
content_type = "application/x-www-form-urlencoded;charset=utf-8"
client_id = "amzn1.application-oa2-client.6a48XXXXXXX408"
client_secret = "592XXXXxxxxxxx6"
scope = "alexa::proactive_events"
grant_type = "client_credentials"
data = {"grant_type": grant_type, "client_id": client_id, "client_secret": client_secret, "scope": scope}
r = requests.post("https://api.amazon.com/auth/O2/token", data=data, headers={"content-type": content_type})
speech = render_template("welcome")
reprompt = render_template("welcome_reprompt")
return question(speech).reprompt(reprompt)
That is the response I get:
{'error_description': 'The request has an invalid parameter : scope', 'error': 'invalid_scope'}
Since one of the reason you get the invalid scope is that you dont have the events included in your skill manifest I include some steps here. I found quite cumbersome to use the SMAPI to update the skill manifest so instead I used ask cli.
install ask-cli: get authorization code for your amazon acount. In my case the backend is not an AWS lambda function but an external web server
get the skill manifest in json format:
ask api get-skill -s "amzn1.ask.skill.ZZZYYYZZ" --stage development > skill.json
Add the notifications permission and the events elements to the manifest:
{
"name": "alexa::devices:all:notifications:write"
}
and
"events": {
"publications": [
{
"eventName": "AMAZON.AAABBBCC"
}
],
"endpoint": {
"uri": "https://XXXYYYZZ:443/whatevercontext"
}
}
update the manifest:
ask api update-skill -s "amzn1.ask.skill.ZZZYYYZZ" --stage development -f skill.json
enable the notifications in the alexa app for your specific skill
Now you should be able to get the token and next step is to send the notification to the device
Have you tried making the API call via any other method? I just tried that with Postman and it worked for me.
My Python's a bit rusty, but here's the self generated code from Postman for Python. May be this should help?
import http.client
conn = http.client.HTTPConnection("api,amazon,com")
payload = "grant_type=client_credentials&client_id=amzn1.application-oa2-client.whatever-value&client_secret=client-secret&scope=alexa%3A%3Aproactive_events&undefined="
headers = {
'Content-Type': "application/x-www-form-urlencoded"
}
conn.request("POST", "auth,O2,token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
As Karthik asked previously have you tried the call via postman? I first suggest trying to via postman before you trying to code it.
If the issue still persists its most likely because you haven't included the necessary permissions required for Proactive Events in your Skill Manifest.
To add the necessary permissions to Skill Manifest you need to use the Skill Management API & ASK Cli.
Follow this section of the documentation and visit the links referenced there to correctly add the required permissions to your skill - https://developer.amazon.com/docs/smapi/proactive-events-api.html#onboard-smapi
Once you have successfully added the events and publications with a skill schema you should be able to successfully generate a token.
Please feel to ask if you want me to elaborate more on the exact steps.
Cheers!
This is what I have tried and it worked:
amazon_token_url = "https://api.amazon.com/auth/O2/token"
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
body = "grant_type=client_credentials&client_id=amzn1.application-oa2-client.XXXYYYZZ&client_secret=ZZZYYYXXX&scope=alexa::proactive_events"
log.debug("Sending token request with body: %s", body)
resp = requests.post(amazon_token_url, data=body, headers=headers)
resp_json = json.loads(resp.content.decode('utf-8'))
if (resp.status_code < 299) and (resp.status_code > 199):
log.debug("token received from Amazon")
log.debug("Content : %s", resp.content)
token = resp_json["access_token"]
return token
I used python 3.6 and I want to post video stream to aws kinesis with API.
I used python aws client to create stream and GetDataEndPoint but when I want to post my data with my custom request (PutMedia doesn't include in python client actually), I get an error Unable to determine service/operation name to be authorized.
I've follow the api doc of aws kinesis video media PutMedia and GetMedia.
So I start by getting endpoint with GetDataEndPoint with client method:
response = client.get_data_endpoint( # aws client method
StreamName=STREAM_NAME,
APIName='PUT_MEDIA'
)
end_point = response['DataEndpoint'] # https://s-EXAMPLE.kinesisvideo.eu-west-1.amazonaws.com
and I post my data at this url:
headers = {
"x-amzn-stream-arn": STREAM_ARN,
"x-amzn-fragment-timecode-type": "ABSOLUTE",
"x-amzn-producer-start-timestamp": start_tmstp
}
# Sign header...
response = requests.post(end_point, data=data, headers=headers) # 403 - Unable to determine service/operation name to be authorized
So I don't understand why I get this error... I've found this troubleshooting on aws doc. But they say we must specify ApiName parameter. What I do...
This error might occur if the endpoint is not properly specified. When you are getting the endpoint, be sure to include the following parameter in the GetDataEndpoint call, depending on the API to be called:
I'm also wondering if the GetMedia method is actually implemented in client as they say here because when I debug this method, client don't call GetDataEndPoint and so make request at https://kinesisvideo.region.amazonaws.com insteed of https://ID_EXAMPLE.kinesisvideo.region.amazonaws.com. So method get error Unable to determine service/operation name to be authorized as explained in troubleshooting
The error you're getting is because you're probably providing the endpoint without the "action" that in your case would be putMedia.
Try to append /putMedia to your endpoint and don't forget to specify the "content-type": "application/json" header.
Btw you have also to generate the v4 signatures for your request. You can use a lib or follow this python guide to do it.
I'm working with bitbucket pipelines to build and upload docker images automatically. We use AWS for our docker repo and they change their login credentials every 12 hours, so we need to retrieve and update the environment variables being used by bitbucket so that it can push the images to aws. I've written the following code using python requests to try to update the environment variables for docker user and password but am getting a "500 Internal Server Error" from bitbucket.
def update_pipeline_variable(uuid, name, value, token):
endpoint = 'https://api.bitbucket.com/2.0/repositories/myuser/myrepo/pipelines_config/variables/{{{variable_uuid}}}?access_token={token}'.format(
variable_uuid=uuid,
token=token
)
body = {
'value': value,
'key': name
}
headers = {"Authorization": "Bearer {token}".format(token=token)}
r = requests.put(endpoint, json=body, headers=headers)
if r.status_code == 200:
print('Successfully updated {variable_name} environment variable.'.format(variable_name=name))
return None
raise RuntimeError('The following error occurred while updating the environment: {error}'.format(error=r.content))
If I remove the access token from the request url and keep it only in the auth header, then I get a 404 instead of a 500. I know the tokens and uuids are valid because I am able to make the request successfully using Postman, so it's something specific to my python implementation. I also tried using the oauth2 requests library with exactly the same results.
I'm implementing a push notifications mechanism for my android app.
Right now I'm trying to run a small test just to see that I manage to send push notifications from a python server via http to GCM, and to recieve it successfuly in an android client.
Client code is exactly as in google's tutorial:
http://developer.android.com/google/gcm/client.html
There's a main activity called DemoActivity which is responsible for registering or retrieving an already existed a registration id, and two classes GcmIntentService and GcmBroadcastReceiver responsible for handling the messags from the GCM server to the app.
Of course, I've set the SENDER_ID correctly, and I do manage to get a registration ID for my client app.
Now for the server:
In the server I always recieve the following error:
HTTP Error 401: Unauthorized
This is my server code:
url = "https://android.googleapis.com/gcm/send"
headers = { 'Content-Type' : 'application/json', 'Authorization': 'key=' + SERVER_API_KEY }
values = { 'registration_ids': [CLIENT_REGID]
, 'data': {'test': 'test} }
data = urllib.urlencode(values)
req = urllib2.Request(url, json.loads(values), headers)
response = urllib2.urlopen(req)
the_page = response.read()
self.response.out.write(the_page)
For security reasons I omitted the server api key and the client registration id (they're hard-coded), but I double and triple checked them and they're correct. Also, I made sure the server API key was formed correctly (Credentials -> Create new key -> Server key) and also made sure "Any IP allowed".
All solutions I found on the internet was related to a mistake in the server api or something like that but I already checked that.
Thanks for helpers!
edit:
added 'key=' in the header, but now I recieve Bad request error (HTTP code 400)
another edit:
changes the values object abit and sent it using json.loads, but not I have this error in the client (means it finally recieves a notification from server!!):
Unable to instantiate receiver GcmBroadcastReceiver
Any ideas? I copied the sample project from google as is, so I don't have any idea what's wrong here.
The auth header should be (note the key= part):
Authorization:key=<your_key_here>
so you should set headers like this:
headers = { 'Content-Type' : 'application/json', 'Authorization': 'key='+SERVER_API_KEY }
I believe the issue is that you're sending urlencoded payload, when telling the server to expect json. Try changing data to a json object, as a string: data ="{ 'registration_ids':...}"