I can't get Google Adwords Customers Campagin inform - ruby-on-rails

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'

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'])

boto3 list all accounts in an organization

I have a requirement that I want to list all the accounts and then write all the credentials in my ~/.aws/credentials file. Fir this I am using boto3 in the following way
import boto3
client = boto3.client('organizations')
response = client.list_accounts(
NextToken='string',
MaxResults=123
)
print(response)
This fails with the following error
botocore.exceptions.ClientError: An error occurred (ExpiredTokenException) when calling the ListAccounts operation: The security token included in the request is expired
The question is , which token is it looking at? And if I want information about all accounts what credentials should I be using in the credentials file or the config file?
You can use boto3 paginators and pages.
Get an organizations object by using an aws configuration profile in the master account:
session = boto3.session.Session(profile_name=master_acct)
client = session.client('sts')
org = session.client('organizations')
Then use the org object to get a paginator.
paginator = org.get_paginator('list_accounts')
page_iterator = paginator.paginate()
Then iterate through every page of accounts.
for page in page_iterator:
for acct in page['Accounts']:
print(acct) # print the account
I'm not sure what you mean about "getting credentials". You can't get someone else's credentials. What you can do is list users, and if you want then list their access keys. That would require you to assume a role in each of the member accounts.
From within the above section, you are already inside a for-loop of each member account. You could do something like this:
id = acct['Id']
role_info = {
'RoleArn': f'arn:aws:iam::{id}:role/OrganizationAccountAccessRole',
'RoleSessionName': id
}
credentials = client.assume_role(**role_info)
member_session = boto3.session.Session(
aws_access_key_id=credentials['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
aws_session_token=credentials['Credentials']['SessionToken'],
region_name='us-east-1'
)
However please note, that the role specified OrganizationAccountAccessRole needs to actually be present in every account, and your user in the master account needs to have the privileges to assume this role.
Once your prerequisites are setup, you will be iterating through every account, and in each account using member_session to access boto3 resources in that account.

graph api get public events with rails/koala works only for some sites

This is my code
Koala.config.api_version = 'v2.3'
#oauth = Koala::Facebook::OAuth.new 'app_id', 'app_secret'
#graph = Koala::Facebook::API.new #oauth.get_app_access_token
#events = #graph.get_object('141991029192409/events')
which works fine. If I try to fetch the events from another site like
#events = #graph.get_object('161335993890217/events')
I get this error
GraphMethodException, code: 100, message: Unsupported get request.
Please read the Graph API documentation at
https://developers.facebook.com/docs/graph-api [HTTP 400]
That page is likely restricted in some way (alcohol related content, age, location) – and that means you need to use a user access token instead of the app access token. (Or a page access token, if you have admin control over that page.)
With a user access token, Facebook uses the information about that user to determine whether or not they are allowed to see the page. An app access token could be used by “anyone”, and therefor can not be used to access such restricted pages.

Twitter 3-legged authorization in Ruby

I am trying my hand ruby on rails. Mostly I have written code in Sinatra. Anyway this question may not have to do anything with framework. And this question may sound a very novice question. I am playing with Twitter 1.1 APIs and OAuth first time.
I have created an app XYZ and registered it with Twitter. I got XYZ's consumer key i.e., CONSUMER_KEY and consumer secret i.e. CONSUMER_SECRET. I also got XYZ's own access token i.e ACCESS_TOKEN and access secret i.e. ACCESS_SECRET
XYZ application type: Read, Write and Access direct messages
XYZ callback URL: http://www.mysite.com/cback
And I have checked: Allow this application to be used to Sign in with Twitter
What I am trying to do is very simple:
1) Users come to my website and click a link Link your twitter account (not signin with twitter)
2) That opens twitter popup where user grants permission to XYZ to perform actions on his/her behalf
3) Once user permits and popup gets closed, XYZ app gets user's access token and secret and save in the database.
4) Then XYZ uses that user's token and secret to perform actions in future.
I may be moron that such work flow has been implemented on several thousands sites and Twitter API documentations explain this 3-legged authentication, still I am unable to figure it out.
I have read https://dev.twitter.com/docs/auth/3-legged-authorization and https://dev.twitter.com/docs/auth/implementing-sign-twitter Unfortunately no ruby code found on internet that explains with step by step example.
What link should be used to open twitter authentication page when user clicks Link your twitter account.
Can anyone here, write some pseudo code with my pseduo credential above to achieve my goal from beging till end of this work flow? Thanks.
UPDATE:
I started with requesting request token as
require 'oauth'
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET,
{ site: "https://twitter.com"})
request_token = consumer.get_request_token oauth_callback: 'http://www.mysite.com/tauth'
redirect_to request_token.authorize_url
I'm not familiar with ROR but here is the workflow of the OAuth 'dance' that you need to follow when the user clicks your button:
Obtain an unauthorized request token from Twitter by sending a
request to
POST https://api.twitter.com/oauth/request_token
signing the request using your consumer secret. This will be done in the background and
will be transparent to the user.
You will receive am oauth_token and oauth_token_secret back from
twitter.
Redirect the user to
https://api.twitter.com/oauth/authorize?oauth_token=[token_received_from_twitter]
using the oauth token value you received from Twitter in step 2.
When the user authorizes your app they will be redirected to your
callback url with oauth_token and oauth_verifier appended to the
url. i.e.
http://www.mysite.com/cback?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifer=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
Convert the request token into an access token by sending a signed
request along with the oauth_verifier to
POST
https://api.twitter.com/oauth/access_token
signing your request
with your consumer secret and the token secret received in step 2.
If everything goes ok, you will receive a new oauth_token and
oauth_token_secret from Twitter. This is your access token for the
user.
Using the access token and secret received in step 6 you can make
Twitter api calls on behalf the the user by sending signed requests
to the appropriate api endpoints.
Hope you solved your problem by this time, but I built this sample Sign in with Twitter ruby web app that provide all explanation you need to do this integration. Below there's a class that implements all necessary methods with comments:
require "net/https"
require "simple_oauth"
# This class implements the requests that should
# be done to Twitter to be able to authenticate
# users with Twitter credentials
class TwitterSignIn
class << self
def configure
#oauth = YAML.load_file(TWITTER)
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 1)
def request_token
# The request to get request tokens should only
# use consumer key and consumer secret, no token
# is necessary
response = TwitterSignIn.request(
:post,
"https://api.twitter.com/oauth/request_token",
{},
#oauth
)
obj = {}
vars = response.body.split("&").each do |v|
obj[v.split("=").first] = v.split("=").last
end
# oauth_token and oauth_token_secret should
# be stored in a database and will be used
# to retrieve user access tokens in next requests
db = Daybreak::DB.new DATABASE
db.lock { db[obj["oauth_token"]] = obj }
db.close
return obj["oauth_token"]
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 2)
def authenticate_url(query)
# The redirection need to be done with oauth_token
# obtained in request_token request
"https://api.twitter.com/oauth/authenticate?oauth_token=" + query
end
# See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 3)
def access_token(oauth_token, oauth_verifier)
# To request access token, you need to retrieve
# oauth_token and oauth_token_secret stored in
# database
db = Daybreak::DB.new DATABASE
if dbtoken = db[oauth_token]
# now the oauth signature variables should be
# your app consumer keys and secrets and also
# token key and token secret obtained in request_token
oauth = #oauth.dup
oauth[:token] = oauth_token
oauth[:token_secret] = dbtoken["oauth_token_secret"]
# oauth_verifier got in callback must
# to be passed as body param
response = TwitterSignIn.request(
:post,
"https://api.twitter.com/oauth/access_token",
{:oauth_verifier => oauth_verifier},
oauth
)
obj = {}
vars = response.body.split("&").each do |v|
obj[v.split("=").first] = v.split("=").last
end
# now the we got the access tokens, store it safely
# in database, you're going to use it later to
# access Twitter API in behalf of logged user
dbtoken["access_token"] = obj["oauth_token"]
dbtoken["access_token_secret"] = obj["oauth_token_secret"]
db.lock { db[oauth_token] = dbtoken }
else
oauth_token = nil
end
db.close
return oauth_token
end
# This is a sample Twitter API request to
# make usage of user Access Token
# See https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
def verify_credentials(oauth_token)
db = Daybreak::DB.new DATABASE
if dbtoken = db[oauth_token]
# see that now we use the app consumer variables
# plus user access token variables to sign the request
oauth = #oauth.dup
oauth[:token] = dbtoken["access_token"]
oauth[:token_secret] = dbtoken["access_token_secret"]
response = TwitterSignIn.request(
:get,
"https://api.twitter.com/1.1/account/verify_credentials.json",
{},
oauth
)
user = JSON.parse(response.body)
# Just saving user info to database
user.merge! dbtoken
db.lock { db[user["screen_name"]] = user }
result = user
else
result = nil
end
db.close
return result
end
# Generic request method used by methods above
def request(method, uri, params, oauth)
uri = URI.parse(uri.to_s)
# always use SSL, you are dealing with other users data
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# uncomment line below for debug purposes
#http.set_debug_output($stdout)
req = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri)
req.body = params.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
req["Host"] = "api.twitter.com"
# Oauth magic is done by simple_oauth gem.
# This gem is enable you to use any HTTP lib
# you want to connect in OAuth enabled APIs.
# It only creates the Authorization header value for you
# and you can assign it wherever you want
# See https://github.com/laserlemon/simple_oauth
req["Authorization"] = SimpleOAuth::Header.new(method, uri.to_s, params, oauth)
http.request(req)
end
end
end
More detailed explanation at:
https://github.com/lfcipriani/sign_in_with_twitter_sample

How to authenticate to flickr with Flickraw gem

I want to upload a photo but need to authenticate with flickr in order to do so. I am using the flickraw gem but don't understand the instructions below:
require 'flickraw'
FlickRaw.api_key="... Your API key ..."
FlickRaw.shared_secret="... Your shared secret ..."
token = flickr.get_request_token(:perms => 'delete')
auth_url = token['oauth_authorize_url']
puts "Open this url in your process to complete the authication process : #{auth_url}"
puts "Copy here the number given when you complete the process."
verify = gets.strip
begin
flickr.get_access_token(token['oauth_token'], token['oauth_token_secret'], verify)
login = flickr.test.login
puts "You are now authenticated as #{login.username}"
rescue FlickRaw::FailedResponse => e
puts "Authentication failed : #{e.msg}"
end
Can someone explain to me what this code is doing and how I should use it.
First , you should open http service
rails server
On the Console , you will see
Open this url in your process to complete the authication process : http://xxxx.xxxx.xxxx.xxxx........
you have to copy the url and post it on your browser.
After log in , you will get a number , like
xxx-xxx-xxx
just copy it onto your console!
Create a new Flickr app. Get the api key and shared secret from there.
"flickr.get_request_token" creates a request oauth token from flickr. You might want to set permissions to :write if you want to upload instead of :delete
auth_url is where you have to redirect to. That url also contains the oauth request tokens that you just created.
Once you are in auth_url page ( for this you have to login to your Yahoo! account), you can authorize your app to access your flickr account. This gives a verification id.
Use that verification id to you can get the oauth access tokens using this method call 'flickr.get_access_token'
Once you have the Oauth access tokens, you could do any api queries on flickr that your :perms would allow.
The entire process is described in detail here - http://www.flickr.com/services/api/auth.oauth.html
I submitted a pull request but here is an updated form of the documentation that should make this more clear
== Simple
+#Place near the top of your controller i.e. underneath FlickrController < ApplicationController
require 'flickraw'
+#Create an initializer file i.e. Flickr.rb and place it in config -> initializers folder
FlickRaw.api_key="... Your API key ..."
FlickRaw.shared_secret="... Your shared secret ..."
+#Examples of how the methods work
list = flickr.photos.getRecent
id = list[0].id
...

Resources