I need to get the Instance List of my Google cloud project. So i tried this:
requests.get('https://compute.googleapis.com/compute/v1/projects/clouddeployment-265711/zones/europe-west3-a/instances)
How do i get authorization in python?.
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
}
How do i get my "OAuth 2 access token" for my Google Cloud Project
Here is the full documentation on Server to Server authentication which also includes sample codes for every method supported.
In this GCP Github code, you can see multiple ways of authentication that you might choose from depending on your use-case.
For example with this code sample you can use a service account JSON key for authentication:
# [START auth_api_explicit]
def explicit(project):
from google.oauth2 import service_account
import googleapiclient.discovery
# Construct service account credentials using the service account key
# file.
credentials = service_account.Credentials.from_service_account_file(
'service_account.json')
# Explicitly pass the credentials to the client library.
storage_client = googleapiclient.discovery.build(
'storage', 'v1', credentials=credentials)
# Make an authenticated API request
buckets = storage_client.buckets().list(project=project).execute()
print(buckets)
# [END auth_api_explicit]
UPDATE:
If what you want is simply getting the Bearer token and storing it in a python variable to make a simple GET request:
import os
your_key = os.system('gcloud auth print-access-token')
so your_key will now have the Bearer token that you need to include in your request header
Otherwise, please read through this documentation which explains how to authenticate as an end-user.
Related
I want to use a python script to retrieve the policies I have created into BigQuery. The issue is regarding themissing required authentication credential. It is said the script is Expecting OAuth 2 access token, login cookie or other valid authentication credential. But I am not sure where to find it and where to position it in my script. Someone can help me please.
My code:
import requests
response = requests.get("https://bigquery.googleapis.com/bigquery/v2/projects/project123/datasets/Dataset123/tables/Test/rowAccessPolicies")
response.json()
Desired output:
{
"rowAccessPolicies": [
{
"rowAccessPolicyReference": {
"projectId": "project123",
"datasetId": "Dataset123",
"tableId": "Test",
"policyId": "test_2"
},
"filterPredicate": "gender = \"M\"",
"creationTime": "2021-11-09T09:45:35.181602Z",
"lastModifiedTime": "2021-11-09T09:45:35.181602Z"
}
]
}
Actual ouptut:
{'error': {'code': 401,
'message': 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
'status': 'UNAUTHENTICATED',
'details': [{'#type': 'type.googleapis.com/google.rpc.ErrorInfo',
'reason': 'CREDENTIALS_MISSING',
'domain': 'googleapis.com',
'metadata': {'method': 'google.cloud.bigquery.v2.RowAccessPolicyService.ListRowAccessPolicies',
'service': 'bigquery.googleapis.com'}}]}}
As said in your message: "Request is missing required authentication credential". You should provide the credentials in your request. You have several ways to do so:
add the credentials in the headers (depending on the type of authentication you have)
use Google Api Core (https://googleapis.dev/python/google-api-core/latest/auth.html)
or use the Google Cloud Python lib which has this procedure include (https://github.com/googleapis/google-cloud-python)
Problem :
I need to get a list of certificates of apps registered under Azure AD and renew the ones which are expiring.
I was able to get the apps related details through Microsoft Graph API > applications. But, the issue is the bearer token refreshes every time in 1 hr. Since I want this task to be automated, I need to create a fresh token always.
I got some reference of Azure SDK for identity-based authentication but the package function is returning a credential, not a token (bearer token) to be used inside the rest API header Authorization
Code:
from azure.identity import DefaultAzureCredential
default_credential = DefaultAzureCredential()
References:
Azure api or sdk to get list of app registrations and the certificates associated with them
Ok after a lot of debugging and surfing the internet, I was able to find the RestAPI way to get the bearer token.
data = {
"client_id":"add your client id",
"scope": "add scope ex: User.read Directory.read.All",
"grant_type": "password", [don't modify this one since you are providing the password]
"username": "your username",
"password": "your password",
"client_secret": "client secret"
}
headers = {
"Host": "login.microsoftonline.com",
"Content-Type": "application/x-www-form-urlencoded"
}
data = requests.post(f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token', data=data, headers=headers)
You will receive a json consisting of access token and related details.
Do remember to provide the permissions in the azure portal> Azure AD > app registrations > your app > API permissions (grant consent)
: )
I'm trying to have a custom message be sent when adding permissions to a file, while the invitation gets sent, the custom message does not appear. This is my snippet if someone can tell me what I am doing wrong, I'd appreciate it =)
(Python3.7)
from googleapiclient.discovery import build
def set_permissions(file_id):
permissions = {
"type": "user",
"role": "writer",
"emailAddress": 'my-email#domain.com',
"sendNotificationEmail" : True,
"emailMessage" : "some message with URL string"
}
service = build('drive', 'v3', credentials=Auth(), cache_discovery=False)
request = service.permissions().create(
fileId= file_id,
body=permissions,
fields='id'
)
return request.execute()
I've tried going through the docs here : https://developers.google.com/drive/api/v3/reference/permissions/create
But don't see any typos in the field names or anything.
You want to create a permission using Drive API v3.
You want to add emailMessage.
You want to achieve this using googleapis with python.
You have already been able to use Drive API.
Modified script:
When your script is modified, please modify as follows.
def set_permissions(file_id):
permissions = { # Modified
"type": "user",
"role": "writer",
"emailAddress": 'my-email#domain.com',
}
service = build('drive', 'v3', credentials=Auth(), cache_discovery=False)
request = service.permissions().create(
fileId= file_id,
body=permissions,
fields='id',
sendNotificationEmail=True, # Added
emailMessage="some message with URL string" # Added
)
return request.execute()
References:
Permissions: create
Drive API . permissions
I'm following the Get access without a user guide to write a Python script that will call Microsoft Graph.
This script will be scheduled from cron so it cannot get admin consent (therefore authorize using Client Credentials). I am able to successfully obtain a token using this call:
request_url = "https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/token"
data = {
'Host' : 'login.microsoftonline.com',
'Content-Type' : 'application/x-www-form-urlencoded',
'client_id' : 'my-client-id-1234',
'scope' : 'https://graph.microsoft.com/.default',
'client_secret' : client_secret,
'grant_type' : 'client_credentials'
}
response = requests.post(url = request_url, data = data)
I then try to get a user listing with this call, using the valid token:
request_url = "https://graph.microsoft.com/v1.0/users"
headers = {
'Authorization' : 'Bearer ' + token,
'Host' : 'graph.microsoft.com'
}
response = requests.get(url = request_url, headers = headers)
The problem is that I get an Authorization_IdentityNotFound error:
<Response [401]>
{
"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "2257f532-abc4-4465-b19f-f33541787e76",
"date": "2018-03-27T19:11:07"
}
}
}
These are the permissions I've selected:
Any idea how to fix this error?
For others running into this issue, I was also getting this error until found out the documentation omits a very important caveat:
For client credentials, if the app belongs to a work or school (organization) context then for https://login.microsoftonline.com/common/oauth2/token replace common with a tenantId or domain name
See
Authorization_IdentityNotFound on Microsoft Graph API request
First things first, you can go ahead an remove all those Delegated Permission scopes. If you're using the Client Credentials Grant, you will only be using Application Permission scopes.
Second, you need to execute the Admin Consent flow before you can use Client Credentials. This is done by having a Global Admin from the tenant authenticate and accept your scope request:
https://login.microsoftonline.com/common/adminconsent?client_id=[APPLICATION ID]&redirect_uri=[REDIRECT URI]
You can read more about Admin Consent here: v2 Endpoint and Admin Consent
I am trying to generate acces token from refresh token in django.
I am using Oauth2.
I am using oauth2 internal url for generating access token
i.e, 127.0.0.1:8000/o/token/
I am testing this in Rest Console.
My request is:
{ "client_id": "m5JjAzkqOCdH9MC4KV9EAjKuNhdMv2TyNDXgD6T7", "client_secret": "6C495R1BiA0lfXgm7lh0Zvqc6ugB7H6srlwSCLwyVNgoKqK7xGVQbB63Hj97E7fw3tWIgG7tnv9K5nwInaKPaaqSy4FLm8jaBdTPZ8YzlCJMkuiWNbIwc0ltFB7H9cgq",
"username": "lalit198910",
"grant_type": "refresh_token",
"token type" : "Bearer",
"refresh_token": "1svsHogo5tq6UxkiY55iMvMpWnGRsn" }
the error i am getting is:
"error": "unsupported_grant_type"
my content type is :
application/x-www-form-urlencoded
In Custom headers i have :
authorization type: bearer
value :3nKkSW9TEPjusuy2PzKhFxoTkFlqQC(Access token)
I have solved this problem,
I was using RAW BODY to pass my request data instead of using Request Paramters