Postman API get access token - python

I am not trying to get an access token to any other website using postman, I am trying to get an access token for the actual Postman website!!
I have a script that I am working to implement for Azure and I need to use postman to send a POST request and download the response body. Based on my research, to be able to use the POST request to download the response body, I need to pass Postman an access token as a parameter for my download function.
This is my auth method to get the access token for postman:
def authenticate_postman(api_key, username, password):
''' Authenticate into Postman API and get a valid access token
'''
global access_token
url = "https://api.postman.com/oauth/token"
headers = {
"X-Api-Key": api_key,
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "password",
"username": username,
"password": password
}
response = requests.post(url, headers=headers, data=data)
if response.status_code != 200:
print(response.json())
raise Exception("Failed to authenticate. HTTP Error {}".format(response.status_code))
access_token = response.json()["access_token"]
return access_token
api_key, username, password come from os.environ
I get this error:
{'error': {'name': 'notFound', 'message': 'Requested resource not found'}}
I am not sure why it doesn't work or how I can fix this. Any help would be appreciated!

Related

Azure Active directory return 403 as Access denied

I am new to using this type of trying to get the user details in my org using python flask server by hitting the
URL : https://graph.microsoft.com/v1.0/me/
Request headers:
'Content-Type': "application/json", 'Authorization': accessToken
Response:
Access Denied
The page you requested has been blocked
any suggestions please?
From the graph URL , able to get the response from python code base we got the Access Denied.
method in python:
enter code here
def get_user_details_(access_token: str):
url = "https://graph.microsoft.com/v1.0/me"
headers = {'Content-Type': "application/json",
'Authorization': access_token
}
response = requests.get(url, headers=headers, verify=False)
print("response **** ", response.text)
response = response.json() if response else {}
return response
enter image description here
To resolve the above issue, We can follow the below workaround;
Make sure that you have following permissions given for your application so that, while calling the API it can able to read and give the desired result.
OUTPUT RESULT FOR REFERENCE:-
For complete setup please refr this BLOG|Querying Microsoft Graph API with Python by #Ephraim Mwai.
I found the answer.
It is related to Proxy. We need to add proxy details to request object.
proxyDict = {
"http": "http proxy address",
"https": "https proxy address"
}
response = requests.request('GET', url, headers=headers, proxies=proxyDict, verify=False)

Python Citrix Sharefile Token Request giving 400 error

I am trying to make a simple request to get the access token from Citrix ShareFile, but it's throwing 400 error.
I am going exactly as it's mentioned in the documentation, except changing Python2 code with HTTPLib, with Python3 code with Requests. The code is:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content_Type': 'application/x-www-form-urlencoded'}
params = {'grant_type':'password', 'client_id':my_client_id, 'client_secret':my_client_secret, 'username':my_username, 'password':my_password}
response = requests.post(url, params=params, headers = headers)
print(response.status_code, response.reason)
I get the following response:
400 Bad Request
I also added urllib.parse.urlencode to params, but am still getting the same response error
response = requests.post(url, params=urllib.parse.urlencode(params), headers = headers)
Request guidance on what am I doing wrong. TIA
It could be the password, in the context of Sharefile it means app_password and not the password used to login to website. Or response_type to 'code'.
SF Auth is through OAuth2 with a GrandType: OAuth2 Password Grant
This way works for me:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'response_type': 'code',
'grant_type': 'password',
'client_id': '<YOUR CLIENT ID>',
'client_secret': '<YOUR SECRET>',
'username': '<USERNAME>',
'password': '<APP_PASSWORD>' # not regular password to login using web
}
response = requests.post(url, data=data, headers=headers)
Response contains token and refresh token.
When I add content-type my issue solved.
Check and add valid content-type

API call (python) from twitter returns Unauthorized error but works on Postman

I recently tried getting organic metrics for a tweet using postman. My trial on postman was successful, I used Oauth 1.0 for authorization. And from this example I extracted the python syntax for the API request.
The following is the sample code:
import requests
url = "https://api.twitter.com/2/tweets/123456789?tweet.fields=non_public_metrics,organic_metrics"
payload={}
headers = {
'Authorization': 'OAuth oauth_consumer_key="xxxxxxxxxx",oauth_token="xxxxxxxxxx",oauth_signature_method="HMAC-SHA1",oauth_timestamp="123432343",oauth_nonce="abcdefgh",oauth_version="1.0",oauth_signature="xxxxxxx"'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
However, when i try to run this as a standalone python script it returns unauthorized error while through postman it works. May I ask what could be the cause of this behavior?
Error:
{
"title": "Unauthorized",
"type": "about:blank",
"status": 401,
"detail": "Unauthorized"
}
Look forward to the suggestions! Thanks.
To work with user context on twitter API use requests_oauthlib class.
You can find a simple implementation below in python:
consumer_key = "xxxxxxxx"
consumer_secret = "xxxxxxxxx"
access_token = "xxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxx"
from requests_oauthlib import OAuth1Session
params = {"ids": "123234343"}
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=access_token,
resource_owner_secret=access_token_secret,
)
response = oauth.get(
"https://api.twitter.com/2/tweets", params=params
)
This implementation requires you to have the all the key parameters like consumer key, consumer secret, access_token and access token secret. Please visit your twitter dev page to generate all the values (if you are not sure you can follow their docs https://developer.twitter.com/en/docs/authentication/oauth-1-0a/api-key-and-secret )
Thanks, hope it helps others!

Python Discord OAuth2 - Bad Request (Guild.Join)

Hi i'm trying to add a user to my guild using Discord's API.
The Scope I'm using is Guild.Join, Identify and Guilds. identify%20guilds%20guilds.join
The URL Is https://discordapp.com/api.
Here's my code:
#staticmethod
def add_to_guild(access_token, userID):
url = f"https://discordapp.com/api/guilds/{guildId that I cant show}/members/{userID}"
botToken = "<Bot Token I can't SHow haha>"
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
payload = {
'access_token' : access_token
}
response = requests.put(url=url, data=payload, headers=headers)
print(response.text)
when I call this method, I receive this error:
{"message": "400: Bad Request", "code": 0}
I've been through the Discord's Documentation countless of times and searched the internet to no avail.
Can someone please help ? Thanks.
you had to replace data to json
def add_to_guild(access_token, userID):
print(userID)
url = f"{Oauth.discord_api_url}/guilds/<GuildID>/members/{userID}"
headers = {
"Authorization" : "Bot <bottoken>",
"Content-Type": "application/json"
}
payload = {
'access_token' : str(access_token)
}
response = requests.put(url=url, json=payload, headers=headers)
print(response.text)
The userID is enough I am not sure why you want the payload or access token; Try to drop the payload part.
If you are trying to add a user, the user has to agree to grant you some permissions check here https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes so the token I think will be the "Bearer" tokens. Check the doc I've shared.

How to gain an Access Token

I am lost, I have no idea what should I do to get the access token. This is the code that I have tried, please help, please!
This is for Oauth2.0 token, and the API is Ocotoparse.
from octoparse import Octoparse as oct
import requests
host='https://advancedapi.octoparse.com/token'
url=host+'username={onlyfiii}&password={19970909huy}&grant_type=password'
r=requests.post(url)
username='onlyfiii'
password='19970909huy'
{
"access_token": "ABCD1234",
"token_type": "bearer",
"expires_in": 86399,
"refresh_token": "refresh_token"
}
I hope that's not your real password, if it is, change it immediately.
You need to send the request parameter as a form encoded POST request body, not as url parameters.
import requests
import json
url = 'https://advancedapi.octoparse.com/token'
payload = {
'username': 'onlyfiii',
'password': '19970909huy',
'grant_type': 'password',
}
r = requests.post(url, data=payload)
json_response = json.loads(r.text)
access_token = json_response['access_token']
See the API docs:
Request Content Type
application/x-www-form-urlencoded

Categories