Microsoft cloud, how to call API authentication, some authentication information is created there
import os
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.network import NetworkManagementClient
subscription_id = os.environ.get(
'AZURE_SUBSCRIPTION_ID',
'11111111-1111-1111-1111-111111111111') # your Azure Subscription Id
credentials = ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
network_client = NetworkManagementClient(credentials, subscription_id)
AZURE_CLIENT_ID,AZURE_CLIENT_SECRET,AZURE_TENANT_ID,AZURE_ CLIENT_ ID,AZURE_ CLIENT_ SECRET,AZURE_ TENANT_ Where was the ID created?
Related
I am not able to start Azure Vm using python code without using clientId and Secrete Id.
Can we start or stop Azure vm in python without using client_id and secrete id.
Here is the code for reference.
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient,ComputeManagementClientConfiguration
credentials = ServicePrincipalCredentials(
client_id = '<client-id>',
secret = '<key>',
tenant = '<tenant-id>'
)
subscription_id = '<subscription-id>'
compute_config = ComputeManagementClientConfiguration(credentials, subscription_id, api_version='2015-05-01-preview')
compute_client = ComputeManagementClient(compute_config)
resource_group_name = '<resource-group>'
vm_name = '<vm-name>'
result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name)
here we are using client Id and all... but I want to stop my Azure Vm without need of applications id/client id..
you can use azure-identity package for this and DefaultAzureCredential:
from azure.identity import DefaultAzureCredential
credentials = DefaultAzureCredential()
compute_config = ComputeManagementClientConfiguration(credentials, subscription_id, api_version='2015-05-01-preview')
compute_client = ComputeManagementClient(compute_config)
https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python
main advantage - you can use MSI authentication
Im trying to make some GET requests in Google Chronicle using only API KEY.
I found this code but it only work with json credentials:
def call_list_alerts():
import os
from google.oauth2 import service_account
from googleapiclient import _auth
SCOPES = ['https://www.googleapis.com/auth/chronicle-backstory']
SERVICE_ACCOUNT_FILE = os.path.join(os.environ['HOME'], 'bk_credentials.json')
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
http_client = _auth.authorized_http(credentials)
BACKSTORY_API_V1_URL = 'https://backstory.googleapis.com/v1'
LIST_ALERTS_URL = '{}/alert/listalerts?start_time=2019-10-15T00:00:00Z&end_time=2019-10-17T00:00:00Z&page_size=1'.format
(BACKSTORY_API_V1_URL)
response = http_client.request(LIST_ALERTS_URL, 'GET')
if response[0].status == 200:
alerts = response[1]
print(alerts)
else:
err = response[1]
print(err)
How can i achieve this using API key and not service account?
I want to access the listed websites data in the Google Search Console using the Google Sign-In access_token (that one can get as the response when using Google Sign-In).
But, the thing is I can access that data only by using the authorization_code that can be copied from the OAuth2-Consent screen by going to the generated authorize_url and signing in using the registered Google account.
Here's the minimum reproducible version of the code:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
Consider that I'll be provided with the Google Sign-In access-token as the request-parameter from another server which has implemented Google Sign-In feature.
So, again my question is how can I access the same data using that token instead of manually getting the auth_code from the OAuth2 consent screen ?
I have followed the documentation shared by DaImTo in the comments above. And modified the code as shown below:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client import tools, file
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Acquire and store oauth token.
storage = file.Storage('token.json')
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
credentials = tools.run_flow(flow, storage)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
It's working fine now, without any manual interaction for copying and pasting the authorization_code from the OAuth2-Consent screen.
I am writing a python wrapper for fusion tables.
I decided to use google service account for accessing the service. My code is:
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/fusiontables']
credentials = ServiceAccountCredentials.from_json_keyfile_name('__Remak APIS-37c11e21531ad.json', scopes)
http = httplib2.Http()
if not credentials.access_token:
credentials.refresh(http)
service = build('fusiontables', 'v2', http=http)
def test():
table_id = '1esH-YayZegZH69VsiVBq0YK9hxgP-JWTCljRuQUZy'
print(service.query().sql(sql='SELECT * FROM {}'.format(table_id)).execute(http=http))
if __name__ == '__main__':
test()
the output is:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/fusiontables/v2/query?alt=json&sql=SELECT+%2A+FROM+1esH-YayrtegZH6VsiVBq0YK9hxgP-JWTCljRuQUZy returned "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.">
I just enabled this API that is why the daily limit is for sure hasn't reached. I also tried to find the answer in similar topics, but I wasn't succeeded.
Thank you in advance
Finally made it work:
there were one part missed:
credentials.authorize(http)
Now it seems OK
The code is:
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/fusiontables']
KEY = '__Remak APIS-a8cd56ca2b4e.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY, scopes)
http = httplib2.Http()
credentials.authorize(http)
if not credentials.access_token:
credentials.refresh(http)
fusiontables = build('fusiontables', 'v2', http=http)
def test():
table_id = '1esH-YayZegZH97VsiVBq0YK9hxgP-JWTCljRuQUZy'
print(fusiontables.query().sql(sql='SELECT * FROM {}'.format(table_id)).execute())
if __name__ == '__main__':
test()
I want to use gspread and since client authentication is outdated, I'm trying with Oauth2. I'm new to both gspread & Oauth2.
Piecing together from this basic Oauth2 example and the gspread documentation I have the most basic login function.
import gspread
from oauth2client.client import OAuth2WebServerFlow
CLIENT_ID = 'my id'
CLIENT_SECRET = 'my secret key'
flow = OAuth2WebServerFlow(client_id= CLIENT_ID,
client_secret= CLIENT_SECRET,
scope='https://docs.google.com/spreadsheets/',
redirect_uri='http://localhost:80')
gc = gspread.authorize(flow)
The problem is that I get this error.
TypeError: 'OAuth2WebServerFlow' object does not support indexing
from the larger
C:\Python34\lib\site-packages\gspread\client.py:73: Warning:
ClientLogin is deprecated:
https://developers.google.com/identity/protocols/AuthForInstalledApps?csw=1
Authorization with email and password will stop working on April 20, 2015.
Please use oAuth2 authorization instead:
http://gspread.readthedocs.org/en/latest/oauth2.html
""", Warning)
Traceback (most recent call last):
File "C:\Users\family\Desktop\mygspread.py", line 13, in
gc = gspread.authorize(flow)
File "C:\Python34\lib\site-packages\gspread\client.py", line 335, in authorize
client.login()
File "C:\Python34\lib\site-packages\gspread\client.py", line 105, in login
data = {'Email': self.auth[0],
TypeError: 'OAuth2WebServerFlow' object does not support indexing
Since both are official scripts - one from google and the other from burnash, I'm not sure what to change. I know the question is basic, but how do I log in with Python 3.4?
You can use OAUTH 2.0 using 2 ways.
Service account
Calls Google API's on behalf of your application instead of an end
user
Follow here for more details:
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
json_key = json.load(open('gspread-april-2cd … ba4.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)
wks = gc.open("Where is the money Lebowski?").sheet1
Web application
Accessed by web browsers over the network
Follow this blog for more details
import requests, gspread
from oauth2client.client import SignedJwtAssertionCredentials
def authenticate_google_docs():
f = file(os.path.join('your-key-file.p12'), 'rb')
SIGNED_KEY = f.read()
f.close()
scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
credentials = SignedJwtAssertionCredentials('username#gmail.com', SIGNED_KEY, scope)
data = {
'refresh_token' : '<refresh-token-copied>',
'client_id' : '<client-id-copied>',
'client_secret' : '<client-secret-copied>',
'grant_type' : 'refresh_token',
}
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
credentials.access_token = ast.literal_eval(r.text)['access_token']
gc = gspread.authorize(credentials)
return gc
I've figured it out. If anyone else is interested, this is what I needed to do
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
json_key = json.load(open('Gspread-762ec21ac2c5.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email']
, bytes(json_key['private_key']
, 'utf-8')
, scope)
gc = gspread.authorize(credentials)
wks = gc.open("mytestfile").sheet1