Python Simple OAuth access - python

I am trying to access a proprietary web service that has Oauth access. I have no experience with that and I am trying to use ;'requests' and 'requests_oauthlib'.
I have the following access data:
auth_url = 'https://foobar.url.com/oauth/token'
data_url = 'https://foobar.url.com/rest/v1/aname/overview'
API_Key = 'Basic Y2xpY2tleS1hcHA6YXBwLWFjY2Vzcw=='
username ='ausername' password = 'apassword' grant_type = 'password'
The API key should be put in the Header in the Field 'Authorization'
Any examples that fit the above would be appreciated. I cannot find any match with the requests_oauth docs.

Well, requests_oauthlib hasn't provided a way to issue password grant type token. You can try Authlib, the client of Authlib has a similar API, check how to authenticate with password grant type:
https://docs.authlib.org/en/latest/client/oauth2.html#oauth2session-for-password

Related

How Can I get an ID Token while validating using Username and Password?

I am using Python ADAL library to Authenticate a user using Azure Active Directory. I successfully receive the access token post authentication. Now, I want to verify the validity of the access token. I need the ID_TOKEN in this case. How do I get it?
import adal
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/{{tenant_id}}")
token_response = auth_context.acquire_token_with_username_password("https://management.core.windows.net/", username, password, client_id)
In the token response, I get the access_token and refresh_token but I do not receive the id_token. Following a similar question, How to verify JWT id_token produced by MS Azure AD? I used the code to validate the access token but I need the ID_TOKEN.
Any thoughts on getting this would be great.
No need to get the ID_TOKEN, try the code as below.
import adal
import jwt
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/{{tenant_id}}")
token_response = auth_context.acquire_token_with_username_password("https://management.core.windows.net/", username, password, client_id)
token_header = jwt.get_unverified_header(token_response['accessToken'])
For more details, you could refer to this similar issue and this doc.

Python script on adding connection from linkedin

I'm trying to use python-linkedin library here https://github.com/ozgur/python-linkedin
to send an invitation to linkedin contact via script
But on following code:
from linkedin import linkedin
API_KEY = 'wFNJekVpDCJtRPFX812pQsJee-gt0zO4X5XmG6wcfSOSlLocxodAXNMbl0_hw3Vl'
API_SECRET = 'daJDa6_8UcnGMw1yuq9TsjoO_PMKukXMo8vEMo7Qv5J-G3SPgrAV0FqFCd0TNjQyG'
RETURN_URL = 'https://localhost:8000'
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL) #, linkedin.PERMISSIONS.enums.values())
print authentication.authorization_url # open this url on your browser
application = linkedin.LinkedInApplication(authentication)
I get "The redirect_uri does not match the registered value" when pasting authentication.authorization_url into the browser
Can someone please help ? Feel free to suggest any other methods ;)
Thanks
When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL
Take the key value after http://localhost:8000/?code=
add it after the authentication.authorization_code = "the code provided"
use authentication.get_access_token()
then application = linkedin.LinkedInApplication(token='the token provided')
Quick usage example:
from linkedin import server
application = server.quick_api(KEY, SECRET)
application.get_profile()

Using requests to access third-party API needing Oauth2 google authentication

For test automation purpose, I would like to use requests and requests-oauthlib library to access an API.
The API use an oauth2 authentication with google account, however it's not a google API. As my test tool should be able to run unattended, I would like to be able to obtain an access token that I could then refresh automatically for an indefinite amount of time.
Something looking like this example from requests-auth documentation would be great. It involves a manual login once, and then I can refresh the token.
https://requests-oauthlib.readthedocs.io/en/latest/examples/google.html
from requests_oauthlib import OAuth2Session
client_id="xxxx.apps.googleusercontent.com"
client_secret="xxxxx"
redirect_uri = 'https://localhost/callback'
authorization_base_url = "https://accounts.google.com/o/oauth2/auth"
token_url ="https://accounts.google.com/o/oauth2/token"
scope = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
]
google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
# Redirect user to Google for authorization
authorization_url, state = google.authorization_url(authorization_base_url,
access_type="offline", prompt="select_account")
print 'Please go here and authorize,', authorization_url
redirect_response = raw_input('Paste the full redirect URL here:')
# Fetch the access token
google.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
print r.content
However, I need to adapt to my API, and I can't find a way.
I can set authorization_base_url = "https://example.net/.auth/login/google"
and obtain the redirection URL but it doesn't work afterward.
I don't know either what I should set as scope.
Should I get Id and secret from the API provider ?
Or is there other solution ?

MS Graph authentication using python

Trying to write a Python code where I would like to access my calendar and retrieve my schedule.
Not able to get through the authentication phase.
Seen and tested many examples, but all require running a local server where I browse locally and need to click a button and then enter my credentials.
Aiming to perform all of this inside my Python code.
You can achieve this one of two ways:
Using Resource Owner Password Credential flow - This allows you to pass the username and password to Azure AD. Gotcha's here are if there's any extra thing on the auth flow (consent, MFA, password reset) you'll just get a failure.
Using Client Credentials flow - This one requires admin consent. Also, you have to be really careful about this one as this client will have access to ALL info about all users. This should only be used with secure clients, not clients that other users have access to.
Here's a code snippet that showcases both of these:
import adal
import requests
tenant = "contoso.com"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
username = "foo#contoso.com"
password = "mypassword"
authority = "https://login.microsoftonline.com/" + tenant
RESOURCE = "https://graph.microsoft.com"
context = adal.AuthenticationContext(authority)
# Use this for Client Credentials
#token = context.acquire_token_with_client_credentials(
# RESOURCE,
# client_id,
# client_secret
# )
# Use this for Resource Owner Password Credentials (ROPC)
token = context.acquire_token_with_username_password(RESOURCE, username, password, client_id);
graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}'
# /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/
request_url = graph_api_endpoint.format('/me')
headers = {
'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
response = requests.get(url = request_url, headers = headers)
print (response.content)
Will try the above...
What I did to solve this was using this example - https://developer.microsoft.com/en-us/graph/docs/authorization/app_only
The problem was asking for the right permissions for the app in Azure.

Interacting with Azure Key Vault using python w/ rest api

I am very interested in using the new service recently released for secret management within Azure. I have found a few example guides walking through how to interact with key vault via powershell cmdlets and c#, however haven't found much at all in regards to getting started with using the rest API.
The thing I am particularly confused with is the handling of oauth2 w/ active directory. I have written a oauth2 application listener, built a web application with an AD instance and can now generate a "access_token". It is very unclear to me how to proceed beyond this though, as I seem to consistently receive a 401 HTTP resp code whenever attempting to use my access_token to perform a key vault API call.
Any guides / tips on using azure key vault with python would be greatly appreciated!
Here are some steps you'll need to do before the following code will work... Hopefully I remembered everything!
You'll need to have an application in AD with at least get access
note: you need this to get the CLIENT_ID and CLIENT_SECRET anyway
then run:
azure keyvault set-policy --vault-name 'VAULTNAME' --spn CLIENT_ID --perms-to-secrets '["get"]'
You'll also need the id's for your secrets, which you can get with the Azure CLI using:
azure keyvault secret show [vault] [secret]
or
azure keyvault secret show -h # if this is unclear
Copy the key (last argument in the URL)
Then the following code will allow you to query the key vault using oauth2:
import json
import requests
AUTHORITY_HOST = "login.windows.net"
TENANT_ID = < your tenant id >
CLIENT_ID = < your client id >
CLIENT_SECRET = < your client secret >
VAULT = 'MyVault'
data = { "grant_type" : "client_credentials",
"client_id" : CLIENT_ID,
"client_secret" : CLIENT_SECRET,
"resource" : "https://vault.azure.net"
}
secrets = [( "i_like_pie", "8a7680a2cf5e4d539494aa0ce265297" )]
headers = { "Content-Type" : "application/x-www-form-urlencoded" }
r = requests.post("https://login.windows.net/{}/oauth2/token".format(TENANT_ID), data=data, headers=headers)
access_token = r.json()['access_token']
for secret, secret_id in secrets.iteritems():
headers = {"Authorization":"Bearer {}".format(access_token) }
r = requests.get('https://{}.vault.azure.net/secrets/{}/{}?api-version=2015-06-01'.format(VAULT, secret, secret_id), headers=headers)
print('##### {} #####'.format(secret))
print(r.json())
print('')
Here are a couple of things that you can check:
When you make the request for the Bearer token, make sure that you include the "resource" header, and that it is set to "https://vault.azure.net". If you don't, you'll get a token, but you won't be able to access any vault data with it.
When you make a call to the vault.azure.net URL, make sure you include the correct "api-version" It can be found in the API documentation. The current value is "2015-02-01-preview".
Of course, check that the Key Vault Access Policy is set correctly for the vault you are trying to access.
For working with Key Vault's REST API, there's reference documentation and service documentation that should help.
Using Key Vault with Python is now more easily done with the Azure SDK. There are three Python packages for working with existing vault data, and one for creating/managing vaults:
azure-keyvault-certificates (Migration guide)
azure-keyvault-keys (Migration guide)
azure-keyvault-secrets (Migration guide)
azure-mgmt-keyvault
azure-identity is also the package that should be used with these for authentication.
With the SDK, using an access token to work with an existing vault from an authorized application is as easy as creating a credential and client:
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
client = SecretClient("https://{vault-name}.vault.azure.net", credential)
secret = client.get_secret("secret-name")
(I work on the Azure SDK in Python)
When Key Vault returns a 401 response, it includes a www-authenticate header containing authority and resource. You must use both to get a valid bearer token. Then you can redo your request with that token, and if you use the same token on subsequent requests against the same vault, it shouldn't return a 401 until the token expires.
You can know the authority and resource in advance, but it's generally more robust to prepare your code to always handle the 401, specially if you use multiple vaults.
Be sure to only trust on a www-authenticate header of a valid SSL connection, otherwise you might be a victim of spoofing!
I have written a simple python wrapper for the REST APIs for Azure Key Vault.
You can check out out here
AzureKeyVaultPythonSDK
Crust of the logic is here
class AzureKeyVaultManager(object):
section_name="KeyVaultSection"
# Constructor
def __init__(self, fileName="private.properties"):
prop_file=os.path.dirname(os.path.realpath(sys.argv[0])) + "/" + fileName
config = ConfigParser.RawConfigParser()
config.read(prop_file)
self.client_id=config.get(self.section_name,'client.id')
self.client_secret=config.get(self.section_name,'client.secret')
self.tenant_id=config.get(self.section_name,'tenant.id')
self.resource=config.get(self.section_name,'resource')
self.key_vault=config.get(self.section_name,'key.vault')
# Authenticate
def initialize(self):
if self.client_id and self.client_secret and self.tenant_id and self.resource and self.key_vault:
print "Got all the properties from file "
token_url="https://login.windows.net/{0}/oauth2/token".format(self.tenant_id)
payload = {'client_id':self.client_id, 'client_secret':self.client_secret, 'resource':self.resource, 'grant_type':'client_credentials'}
response=requests.post(token_url, data=payload).json()
self.access_token=response['access_token']
else:
raise ValueError("Couldn't get the key vault properties from properties file")
# Get secret from a specific keyvault
def getSecretFromKeyVault(self, secretName, keyVault=None):
if keyVault is None:
keyVault=self.key_vault
endpoint = 'https://{0}.vault.azure.net/secrets/{1}?api-version=2015-06-01'.format(keyVault, secretName)
headers = {"Authorization": 'Bearer ' + self.access_token}
response = requests.get(endpoint,headers=headers).json()
if 'value' in response:
return response['value']
else:
raise ValueError("Value not found in response")

Categories

Resources