Cloud Function & OAuth 2.0 - oauth

I have a issue to use OAuth2.0 on GCP Cloud Function. I use to run this code locally. it works and it open a web browser's page to ask access to my gmail account.
I know that InstalledAppFlow is only use for local application.
SCOPES = ['https://mail.google.com/']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) # <-- Oauth2.0 credential
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
I then tried to do another way using /tmp repesitory to store the token but still doesn't work and I can't see where is the issue ... Do you have any idea ? thank you so much
SCOPES = ['https://mail.google.com/']
CLIENT_SECRET_FILE = 'credentials.json' #OAuth credentials
APPLICATION_NAME = 'Gmail API Python'
def get_credentials():
store = oauth2client.file.Storage("/tmp/tempcredentials.json")
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
return credentials

As stated in the documentation the temporary folder is just for creating temporary files that will be stored in RAM memory and only available for the instance currently executing your code, thus there's no guarantee of persistence between invocations.
You should check this tutorial as it explains how to authenticate from Cloud Functions into Gmail (you will need more than a single function).

Related

Azure DevOps PAT API to be able to list all tokens in organization

Need to obtain the list of all tokens in organization.
Used the token to make a call to https://vssps.dev.azure.com/{organization}/_apis/tokens/pats?api-version=6.1-preview.1
My permission in DevOps are set as the Collection Administrator.
Received response was:
{“$id”:“1”,“innerException”:null,“message”:“The requested operation is not allowed.”,“typeName”:“Microsoft.TeamFoundation.Framework.Server.InvalidAccessException, Microsoft.TeamFoundation.Framework.Server”,“typeKey”:“InvalidAccessException”,“errorCode”:0,“eventId”:3000}
Is there some lack of permissions or do I need to set up something else to get list of tokens in organization?
You don't mention how you get your token, and criteria for authentication flow but I will share my adventure that started similarly yours.
I got your exact error while following this guide: https://learn.microsoft.com/en-gb/azure/devops/organizations/accounts/manage-personal-access-tokens-via-api?view=azure-devops
The token I got from that python code just didn't work.
Then I found this code instead: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/app-aad-token#--username-password-flow-programmatic
While using the same app registration from the link above, I copied my scope and tenantID from the dysfunctional code into this new code, and then go to your app registration --> authentication --> Allow public client flows to yes, see screenshot.
I ran the script after giving the credentials and now the token worked.
Dumping the code for future reference:
# Given the client ID and tenant ID for an app registered in Azure,
# along with an Azure username and password,
# provide an Azure AD access token and a refresh token.
# If the caller is not already signed in to Azure, the caller's
# web browser will prompt the caller to sign in first.
# pip install msal
from msal import PublicClientApplication
import sys
# You can hard-code the registered app's client ID and tenant ID here,
# along with the Azure username and password,
# or you can provide them as command-line arguments to this script.
client_id = '<client-id>'
tenant_id = '<tenant-id>'
username = '<username>'
password = '<password>'
# Do not modify this variable. It represents the programmatic ID for
# Azure Databricks along with the default scope of '/.default'.
scope = [ '2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default' ]
# Check for too few or too many command-line arguments.
if (len(sys.argv) > 1) and (len(sys.argv) != 5):
print("Usage: get-tokens-for-user.py <client ID> <tenant ID> <username> <password>")
exit(1)
# If the registered app's client ID and tenant ID along with the
# Azure username and password are provided as command-line variables,
# set them here.
if len(sys.argv) > 1:
client_id = sys.argv[1]
tenant_id = sys.argv[2]
username = sys.argv[3]
password = sys.argv[4]
app = PublicClientApplication(
client_id = client_id,
authority = "https://login.microsoftonline.com/" + tenant_id
)
acquire_tokens_result = app.acquire_token_by_username_password(
username = username,
password = password,
scopes = scope
)
if 'error' in acquire_tokens_result:
print("Error: " + acquire_tokens_result['error'])
print("Description: " + acquire_tokens_result['error_description'])
else:
print("Access token:\n")
print(acquire_tokens_result['access_token'])
print("\nRefresh token:\n")
print(acquire_tokens_result['refresh_token'])

Azure tableclient in console app using interactive authentication

I'm trying to access Azure Table Storage using the TableClient class, but I want to authenticate using AzureAD credentials via the browser popup.
I have tried 2 approaches and are sure I have things configured correctly in Azure, but I just keep getting
This request is not authorized to perform this operation using this
permission.
Here is test code 1 using MSAL
let app = PublicClientApplicationBuilder.Create("---registered app ID---")
.WithAuthority(AzureCloudInstance.AzurePublic, "---tennant id----" )
.WithDefaultRedirectUri()
.Build()
let! ar = app.AcquireTokenInteractive(["https://storage.azure.com/user_impersonation"]).ExecuteAsync()
let tokenCredential = { new TokenCredential() with
member x.GetTokenAsync(_,_) = task {return AccessToken(ar.AccessToken, ar.ExpiresOn)} |> ValueTask<AccessToken>
member x.GetToken(_,_) = AccessToken(ar.AccessToken, ar.ExpiresOn)}
let tc = new TableClient(Uri("https://--endpoint---.table.core.windows.net/"), "--Table--", tokenCredential)
and test 2 using Azure.Identity
let io = new InteractiveBrowserCredentialOptions(ClientId = "---registered app ID---", RedirectUri = Uri("https://login.microsoftonline.com/common/oauth2/nativeclient"))
let tc = new TableClient(Uri("https://--endpoint---.table.core.windows.net/"), "--Table--", new InteractiveBrowserCredential(io))
I have the app registered in Azure & I have added api permissions for Azure Storage, with Admin consent. My account is a Service Administrator for the tennant so I have full access to the storage account. I have scoured all the docs but just cant see what I'm missing.
To access table data using your Azure AD credentials, your user account should be assigned either Storage Table Data Contributor or Storage Table Data Reader role.
Please assign one of these roles to your user account and re-acquire the token. You should not get the error you are getting then.

I can't get Google Adwords Customers Campagin inform

I want to build a web application. Clients can use the web application to read their google Adwrods accounts information( campagins or budgets ).
First, I use oath2 get client's refresh_token and access_token.
Using the refresh_token, I can get all adwords id under the client by (https://github.com/googleads/google-ads-ruby)
client = Google::Ads::GoogleAds::GoogleAdsClient.new do |config|
config.client_id = "client_id"
config.client_secret = "client_secret"
config.refresh_token = "refresh_token"
config.login_customer_id = "XXX-XXX-XXXX"
config.developer_token = "XXXXXXXXXXXXXXXX"
end
accessible_customers = client.service.customer.list_accessible_customers().resource_names
When I want to get client Adword account information,
resource_name = client.path.customer("XXXXXXXX")
customer = client.service.customer.get_customer(resource_name: resource_name)
I get "GRPC::Unauthenticated: 16:Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential", but the config file can't let me set access_token.
So, where can i set client's access_token, or which step i missed?
The error is telling you that client has not been set up correctly. It could be a bunch of issues from Google account to wrong information. I would check and make sure all the info you are passing in Google::Ads::GoogleAds::GoogleAdsClient.new is correct.
Also, you only need to pass 'login_customer_id' for manager accounts only, it doesn't sound like you are a manager account.
From https://github.com/googleads/google-ads-ruby/blob/master/google_ads_config.rb
# Required for manager accounts only: Specify the login customer ID used to
# authenticate API calls. This will be the customer ID of the authenticated
# manager account. If you need to use different values for this field, then
# make sure fetch a new copy of the service after each time you change the
# value.
# c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'

How generate OAuth for azure vm

I installed Grafana on my Azure virtual machine. Now I want to set OAuth.
In defaults.ini I set the
name = my app
enabled = true
allow_sign_up = true
client_id = with my id
client_secret = with my client_secret
scopes = openid email name
auth_url =
token_url =
api_url =
team_ids =
allowed_organizations =
And this not work. Can anyone have some idea where I wrong.
Do not edit defaults.ini!
Use the following link to create or locate grafana.ini or custom.ini depending on your OS:
https://grafana.com/docs/grafana/latest/installation/configuration/
I would recommend that you copy the block of code for the OAuth provider you want to use to grafana.ini/custom.ini and then edit it to suit your need.
You may have to edit the URL under the [server] settings to allow for the correct redirect when using external OAuth

Retrieve access token in Azure with Ruby SDK/APIs

I am trying to retrieve access token using azure app client id and client secret . Initially I tried with the following python code block
import adal
context = adal.AuthenticationContext(AUTHORITY)
token = context.acquire_token_with_client_credentials(
"https://management.azure.com/",
CLIENT_ID,
CLIENT_SECRET)
This is returning the token without any issue .
I am trying to do the same using Azure Ruby SDK following the contents in https://github.com/Azure/azure-sdk-for-ruby but still not able to get any sample to follow .
I am a beginner in ruby ,can some body please share their experience with me on this ?
Added to my post from here on
Hi ,
Many thanks for your support .
I followed you code and written my code like the below one following your code
require 'adal'
TENANT=<TENANT ID>
CLIENT_ID= <CLIENT_ID>
CLIENT_SECRET =<CLIENT_SECRET >
AUTHORITY = "https://login.windows.net"
auth_ctx = ADAL::AuthenticationContext.new(AUTHORITY, TENANT)
client_cred = ADAL::ClientCredential.new(CLIENT_ID, CLIENT_SECRET)
result = auth_ctx.acquire_token_for_client("https://management.azure.com/", client_cred)
puts result.access_token
But I am getting an error like the following ,
check_host': bad component(expected host component)
In Python it worked for me though .
Following is the full error trace .
F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:593:in `check_host': bad component(expected host component): [https://login.windows.net] (URI::InvalidComponentError)
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:634:in `host='
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:668:in `hostname='
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:187:in `initialize'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:134:in `new'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/generic.rb:134:in `build'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/2.2.0/uri/http.rb:62:in `build'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/authority.rb:95:in `token_endpoint'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/token_request.rb:228:in `oauth_request'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/token_request.rb:182:in `request_no_cache'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/token_request.rb:171:in `request'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/token_request.rb:84:in `get_for_client'
from F:/All_Ruby_On_Rails/ruby-2.2.6-x64-mingw32/lib/ruby/gems/2.2.0/gems/adal-1.0.0/lib/adal/authentication_context.rb:78:in `acquire_token_for_client'
from F:/Selenium_Workspace_HSBC/dsi/azureadallogin.rb:9:in `<main>'
It looks to me the AUTHORITY constant has the issue .Can anybody provide some clue here ?
Welp, he's the copy\paste:
# Create authentication objects
token_provider = MsRestAzure::ApplicationTokenProvider.new(tenant_id, client_id, secret)
credentials = MsRest::TokenCredentials.new(token_provider)
# Create a client - a point of access to the API and set the subscription id
client = Azure::ARM::Resources::ResourceManagementClient.new(credentials)
client.subscription_id = subscription_id
https://github.com/Azure/azure-sdk-for-ruby/tree/master/management/azure_mgmt_resources
Otherwise, you can use the ADAL for Ruby library to get the access token like using Python ADAL as the code you post.
First of all, install adal via gem install adal.
Then,
Follow the adal sample with CLIENT_ID & CLIENT_SECRET to get the access token via the code below using the method acquire_token_for_client.
require 'adal'
AUTHORITY = 'login.windows.net'
auth_ctx = ADAL::AuthenticationContext.new(AUTHORITY, TENANT)
client_cred = ADAL::ClientCredential.new(CLIENT_ID, CLIENT_SECRET)
result = auth_ctx.acquire_token_for_client("https://management.azure.com/", client_cred)
puts result.access_token
Follow the adal sample with USERNAME & PASSWORD to get the access token via the code below.
require 'adal'
AUTHORITY = 'login.windows.net'
user_cred = ADAL::UserCredential.new(username, password)
ctx = ADAL::AuthenticationContext.new(AUTHORITY_HOST, TENANT)
result = ctx.acquire_token_for_user("https://management.azure.com/", CLIENT_ID, user_cred)
puts result.access_token
Hope it helps.

Resources