msal access token not compatible with sharepoint online rest apis - python

I am migrating my code from ADAL to msal library. I have done all the necessary changes .
Trying to get access token by using the following code:
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential=config["secret"] )
result = None
result = app.acquire_token_silent(config["scope"], account=None)
if not result:
result = app.acquire_token_for_client(scopes=config["scope"])
#With this code i am getting the (access token) but when using
headers = self.get_headers()
request = requests.get(url=folder_path, headers=headers, data={})
getting request response [401enter code here].
I cannot access any resource in the _api/web/lists/... api. SharePoint is a bit odd having multiple APIs to get data (Graph endpoint and _api endpoint), but before I dive into an MSAL conversion I wanted to know whether it actually supports access tokens to this SharePoint _api. I have tried without success. I cannot find anything in the Microsoft documentation about the supported APIs so I was hoping for some guidance. Note our application is currently working with ADAL. Thanks!

Related

Authentification issue to BigQuery API REST using Python

I would like to make a HTTP call to this resource :
https://bigquery.googleapis.com/bigquery/v2/projects/{projectId}/jobs
As I read to the documentation I use an API key generated from my GCP project to be authenticated. So with requests I make a simple call like this:
import requests
params = {'key': 'MY_API_KEY'}
base_url = 'https://bigquery.googleapis.com'
project_id = 'MY_PROJECT_ID'
r = requests.get(f'{base_url}/bigquery/v2/projects/{project_id}/jobs', params=params)
Unfortunately it returns a response 401 and I can't figure out why.
Thanks a lot and have a nice day !
Update code after guillaume blaquiere reply :
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
base_url = 'https://bigquery.googleapis.com'
project_id = 'project_id'
credentials = service_account.Credentials.from_service_account_file(
'service_account.json',
scopes=['https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/cloud-platform'],
)
authed_session = AuthorizedSession(credentials)
response = authed_session.request('GET', f'{base_url}/bigquery/v2/projects/{project_id}/jobs')
print(response.json())
# this returns : {'etag': 'tAZvk1k2f2GY8yHaQF7how==', 'kind': 'bigquery#jobList'}
The API Key no longer works for a large number of Google API. Only some legacy continue to accept an API key.
Now, you need an authenticated request. You can find exemple in the google-auth python library documentation. Look at Refresh and Authorized_session.
Don't hesitate to comment if you need help about the credential obtention, I can also help you on this.
EDIT
When you perform the request, it's, by default, only on the current user. In your case, it's the service account when you use the Python code, and your User account when you use the API Explorer (the swagger like in the Google Documentation).
In your case, I guess that your service account has never performed a job (query or load job) and thus, there is no entry for it.
According with the documentation, is you want to see all the user jobs, you have to add the param ?allUsers=true at the end of your URL
response = authed_session.request('GET', f'{base_url}/bigquery/v2/projects/{project_id}/jobs?allUsers=true')

How to write a python script to authenticate to Azure DevOps REST API and get the access token?

How can I authenticate to Azure DevOps REST API in a python script?
I found that there are 2 methods :
Using personal access token (PAT)
Using OAuth 2.0
I am using the second method. Followed the steps in this documentation:
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops
I wrote this function to autherize to azure DevOps using OAuth 2.0:
def get_authenticated():
client_id = < my client ID as a string >
state = "user1"
scope = "vso.graph_manage%20vso.identity_manage%20vso.profile_write%20vso.project_manage%20vso.tokenadministration%20vso.tokens"
callback_URL = < Callback URL to my azure devops account >
# Azure DevOps Services authorization endpoint
Auth_URL = "https://app.vssps.visualstudio.com/oauth2/authorize?client_id=" + client_id + "&response_type=Assertion&state=" + state + "&scope=" + scope + "&redirect_uri=" + callback_URL
headers = {'Accept': 'application/json;api-version=1.0'}
print(Auth_URL)
response = requests.get(Auth_URL,headers = headers)
print(response)
print(response.status_code)
print(response.headers['content-type'])
response.raise_for_status()
But when calling this function, output I am getting is:
<Response [203]>
203
text/html; charset=utf-8
The auth URL is correct because when I tried to access the same URL in a browser it successfully redirects to a form to enter azure user credentials.
The expected behavior of the script is, when the auth_url is requested, Azure DevOps Services should ask the user to authorize. I think that should be done by prompting for username&password in terminal/via a browser.
I am totally new to python scripting and REST APIs.
Can someone help me by pointing out the faults in my code or pointing to some samples?
The http error 203 indicates that the returned metainformation is not a definitive set of the object from a server with a copy of the object, but is from a private overlaid web. In your code,you added headers = {'Accept': 'application/json;api-version=1.0'}, but in fact the content type should be application/x-www-form-urlencoded.
You can use some OAuth2 library for python to authenticate to Azure DevOps REST API, such as OAuthLib. It includes sevelral samples.
Also, you can refer to following topic, hope it is helpful for you.
Tutorial for using requests_oauth2

Python Quickbooks: Unable to get correct authorization URL

I am using Python Quickbooks3 library to connect with QBO. I am doing as given in example but not getting correct URL. Below is my code:
from quickbooks import QuickBooks
clientkey = "qyprdLl476vKE74vVDP99Rl08gn1fr"
clientsecret = "nYFWsjeVspmNBQoIaIfPDABblYYBeX8SAhpDTMXY"
client = QuickBooks(
sandbox=True,
consumer_key=clientkey,
consumer_secret=clientsecret,
callback_url='http://localhost/qbo_token.php'
)
authorize_url = client.get_authorize_url()
request_token = client.request_token
request_token_secret = client.request_token_secret
print(authorize_url,request_token,request_token_secret)
It prints:
('https://appcenter.intuit.com/Connect/Begin?oauth_token=true', u'true', u'Ua3e7ZzPdac98RAZ1PSQJ6fjOEb9COiFDbdEQUdW')
Also, I want to skip browser based authorization as it would only be me using app. How can I do that?
Lots of questions here. For starters:
callback_url='http://localhost/qbo_token.php'
If you're using Python, why are you pointing to .php script for OAuth?
Are you sure you're using your sandbox OAuth consumer key and secret?
Also, I want to skip browser based authorization as it would only be
me using app. How can I do that?
You can't skip it.

Insufficient permission Site verification Google

I want to use python and the verification site api (v1) to verify website in my webmaster tools. In this example I want to get all verified sites using the verification api, because that function doesn't have parameters. (I know that it's possible via the webmaster tools, as well)
#!/usr/bin/python
import httplib2
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
http = httplib2.Http()
storage = Storage('credentials')
storage_verify = Storage('credentials_verify')
credentials = storage.get()
credentials_verify = storage_verify.get()
http_wm = credentials.authorize(http)
http_sv = credentials_verify.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http_wm)
verification_service = build('siteVerification', 'v1', http=http_sv)
site_list = webmasters_service.sites().list().execute()
print(site_list)
# this line generates the error
verified_site_list = verification_service.webResource().list().execute()
print(verified_site_list)
There is an insufficient permission error:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/siteVerification/v1/webResource?alt=json returned "Insufficient Permission">
I have read and write access for the siteVerification api (I've checked my token here: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=TOKEN )
Any ideas what I'm doing wrong or how I can debug the code?
Make sure you read and understand https://developers.google.com/site-verification/v1/invoking in its entirety. Especially you need to appreciate:
Verify a new site
To verify a site,
- First request a verification token by calling getToken.
- Place the token on your site using whatever method you choose.
- Ask Google to verify that the site is yours, using the insert operation.
All you need to do is properly construct two requests, getToken and insert. What "properly" means, is discussed in all detail in the docs I linked above.
If you really need help with code, you need to show a minimal working example so that we can reproduce the error you retrieve.
I found my problem...
These two lines:
http_wm = credentials.authorize(http)
http_sv = credentials_verify.authorize(http)
uses the same http object which isn't allowed.
I use this code now:
http_wm = httplib2.Http()
http_sv = httplib2.Http()
http_wm = credentials.authorize(http_wm)
http_sv = credentials_verify.authorize(http_sv)

Google spreadsheets api do not use OAuth2?

I'm trying to make authorized requests to the google spreadsheets API and all the examples I found requests email and password from the user.
http://www.payne.org/index.php/Reading_Google_Spreadsheets_in_Python
http://www.mattcutts.com/blog/write-google-spreadsheet-from-python/
http://mrwoof.tumblr.com/post/1004514567/using-google-python-api-to-get-rows-from-a-google
Well this problem was solved with OAuth2 protocol which Google implements. I've gone through the OAuth2 process and I have a valid access_token, which I use to interact with Google Drive smoothly:
access_token = get_access_token() # external function
user_agent = request.META['HTTP_USER_AGENT']
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v2', http)
service.files().copy(fileId=k, body=dict(title="Copia")).execute() # this works!
But I can't figure out a way to use the access_token to interact with the spreadsheets API. Does it still uses email and password login?
Thanks!
PS: BTW, I'm using the python gdata package, and please let me know if you have a good reference for it! :)
So, if you already have an access token (maybe you got it by your own via Oauth2 protocol, like me). You can interact with google spreadsheet api passing an instance of AuthSubToken to methods of SpreadsheetsClient.
from gdata.gauth import AuthSubToken
from gdata.spreadsheets.client import SpreadsheetsClient
atok = AuthSubToken(token_string=get_access_token()) # acess token via protocol
data = SpreadsheetsClient().get_worksheets(key, auth_token=atok)

Categories