PHP Google Adwords API get campaigns - oauth

I am using the google adwords API to connect with adwords and list all the campaingns. I am connecting with OAuth to the Adwords account and become an access_token and an refresh_token, which I am saving into the DB.
Now I am trying to make this example:
https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201802/BasicOperations/GetCampaigns.php
But my access_token and my refresh_token are in the database and all the API OAuth2 credentials are in one configuration array.
How to query hte google adwords service with this credentials?

The OAuth2TokenBuilder class referred to in line 81 of your example and copied below has several methods that'll let you set parameters instead of reading them from the config file.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
The fromFile method will read parameters from the config file. Your new code might look something like this:
$oAuth2Credential = (new OAuth2TokenBuilder())
->withClientId(your oauth2 client id here)
->withClientSecret(your oauth2 client secret here)
->withRefreshToken(your stored refresh token here)
->build();
High level overview of some other issues with the Google AdWords API here:
https://pete-bowen.com/how-to-use-the-google-adwords-api-to-automate-adwords

Related

Get Azure AD directory users in a Rails app

I have a Rails 6 application and I want to use Azure Active Directory as an authentication system (with open id connect, saml2 and ldap).
The authentication is done.
Now I am trying to display user information like names or email addresses. I also want to be able to export all users of a directory.
I have tried to set a configuration up like so:
In my Rails app, in the admin panel, an admin can configure Azure AD for my application
in the config, the admin copies and pastes the configuration link provided by Azure AD (a JSON response)
Then, copies and pastes the app client_id
Then, the tenant_id (directory id)
Here is a piece of code that I expected to work:
def update_oidc
identity_provider = IdentityProvider.find_by(provider_type: 'open_id_connect', id: params[:id])
client_id = params[:client_id].strip
metadata_url = params[:metadata_url].strip
tenant_id = params[:tenant_id].strip
metadata = HTTParty.get(metadata_url).parsed_response
identity_provider.update(config: {
metadata: metadata,
metadata_url: metadata_url,
client_id: client_id,
tenant_id: tenant_id,
})
if tenant_id
directory_access_url = "https://graph.windows.net/#{tenant_id}/users?api-version=1.6"
result = HTTParty.get(directory_access_url).parsed_response
identity_provider.directories.find_or_create_by(tenant_id: tenant_id).update(
business_phones: result["business_phones"],
display_name: result["display_name"],
given_name: result["given_name"],
job_title: result["job_title"],
email: result["user_principal_name"],
mobile_phone: result["mobile_phone"],
office_location: result["office_location"],
surname: result["surname"]
)
end
redirect_to identity_provider
end
As the tenant_id is the directory id, i thought that we might be able to access user info this way (and following the Microsoft Docs). The thing is, it doesn't work because even though I'm connected to my Azure AD directory in my app, when I run result = HTTParty.get(directory_access_url).parsed_response, i have an authentication error telling me the token has expired or that i need to be connected.
I don't want to use PowerShell or anything like this. I want to be able to access directories data through my app.
Can someone tell me what i'm doing wrong or come up with an idea ?
Thanks
Just according to your code, I think you want to get the collection of users via the Azure AD Graph REST API Get users using jnunemaker/httparty library.
However, it seems to be missing the required header Authorization with its value like Bearer eyJ0eX ... FWSXfwtQ as the section Authentication and authorization of the offical document Operations overview | Graph API concepts said. Meanwhile, you have done the authentication with OpenID Connect, but Azure AD Graph API requires the access token as Authorization value from OAuth2 as the content below said.
The Graph API performs authorization based on OAuth 2.0 permission scopes present in the token. For more information about the permission scopes that the Graph API exposes, see Graph API Permission Scopes.
In order for your app to authenticate with Azure AD and call the Graph API, you must add it to your tenant and configure it to require permissions (OAuth 2.0 permission scopes) for Windows Azure Active Directory. For information about adding and configuring an app, see Integrating Applications with Azure Active Directory.
Azure AD uses the OAuth 2.0 authentication protocol. You can learn more about OAuth 2.0 in Azure AD, including supported flows and access tokens in OAuth 2.0 in Azure AD.
So I'm afraid you have to get the access token manually via OAuth2 for Azure AD again for using Graph API, or just simply refer to the sample code samples/authorization_code_example/web_app.rb using the adal library of GitHub repo AzureAD/azure-activedirectory-library-for-ruby for Ruby.

How do I authenticate against the Dynamics 365 Data Export Service API?

I've set up something called the Data Export Service for Dynamics 365 so that it replicates into an Azure SQL database. This is working as expected.
I'm trying to find a way to be proactively notified if this service encounters any errors. There does not appear to be a native way to do this through the setup in CRM itself, but they do provide an API. The Swagger page outlining all methods can be found here.
I'm trying to call the GetProfilesByOrganizationId method using Postman:
https://discovery.crmreplication.azure.net/crm/exporter/profiles?organizationId=4ef7XXXX-XXXX-XXXX-XXXX-XXXXXX8a98f&status=true
I'm having issues with authentication and always receive the following error:
"Message": "Received unauthenticated requestRequest Url https://discovery.crmreplication.azure.net/crm/exporter/profiles?organizationId=4ef7XXXX-XXXX-XXXX-XXXX-XXXXXX8a98f&status=true"
I have registered an application in Azure that has permission to access Dynamics 365 on behalf of the authenticated user which in this case is me, the administrator.
I have set the Type to OAuth 2.0 on the Authorization tab of Postman. I have requested an Access Token using the Grant Type of Authorization Code against the above application successfully. This has added a header to the request:
Key: Authorization
Value: Bearer BIGLONGACCESSTOKEN
Despite this header being present I still get the error mentioned above.
The API documentation implies the authentication is OAuth2 Implicit Grant Flow (click on any red exclamation mark in the documentation) but I can't get this to work in Postman. When I try to request a token with this method I get the error:
unsupported_response_type
... in the Postman console.
Any ideas how to authenticate (with Implicit Grant?) against this API in Postman?
(I'd accept C# examples if they're more appropriate, but I'd be surprised if Postman can't show me what I need)
It looks like the code sample shown by Microsoft can work if updated with newer methods and with some extra configuration in Azure that's not documented.
Azure configuration
By installing the Data Export service (and assuming it's all working) you'll have a new Enterprise Application listed in Azure AD as Crm Exporter.
To take advantage of this application and authenticate with the Data Export API you must configure an app of your own.
Go to the App registrations tab in Azure AD and add a new application registration.
Give it a name and set the Application type to Native. The redirect URI doesn't typically matter as long as it's valid.
Click the Manifest button to edit the manifest, change the property oauth2AllowImplicitFlow to true and save the changes.
The only other important configuration is Required permissions which should be set as below:
Windows Azure Active Directory
Delegated permissions
Sign in and read user profile
Data Export Service for Microsoft Dynamics 365 (Crm Exporter)
Delegated permissions
Have access to Data Export Service for Microsoft Dynamics 365 API
You will then need to click Grant Permissions.
C# changes
The updated method looks like this:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
string clientId = "11cfXXXX-XXXX-XXXX-XXXX-XXXXXXXXd020";
string user = "my.username#domain.com";
string password = "PASSWORD";
var authParam= await AuthenticationParameters.CreateFromResourceUrlAsync(
new Uri("https://discovery.crmreplication.azure.net/crm/exporter/aad/challenge")
);
var context = new AuthenticationContext(authParam.Authority, false);
var credentials = new UserPasswordCredential(user, password);
var token = await context.AcquireTokenAsync(authParam.Resource, clientId, credentials).AccessToken;
You can now query the Data Export API by providing the token as a header:
Authorization : Bearer eJ0y........Hgzk
curl -X GET --header 'Accept: application/json' 'https://discovery.crmreplication.azure.net/crm/exporter/profiles?organizationId=MyOrgId&status=true'

Google Sheet API v4

I try to use example "Read multiple ranges":
https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS
from: Google Sheets API v4 example
I replaced "spreadsheetId" with my spreadsheet id.
But when I send GET request (by Postman) I receive:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
Than I used https://developers.google.com/oauthplayground/
I made authorisation for Spreadsheet API v4 with my email and at the end I generated a long link with key and saw correct response with content of my data table.
My question is next:
Why it's imposible to use the example from Google API (https://developers.google.com/sheets/api/samples/reading) only replace the spreadsheet id.
P.s Link to my spreadsheet is public, My spreadsheet is public and available in JSON format and what is correct use of url for Google Spreadsheet API v4 in order to send batchGet with multiple requests?
P.s.s I use another approach and it works but why first approach (v4) doesn't work:
https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values?alt=json
When I tried to combine 2 APIs in one request and received and error "Inconsistent repeating query parameter ranges":
https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS
======================================
Edited:
SpreadSheetID: 1KBk1J7TJCwnayMnTbaysqvFk98kVDdxXWNw2JYc3bW0
Available in incognito mode: Spreadsheet
In JSON format: JSON
Reference: Google Sheets API v4: Read multiple ranges
The same example with SpreadSheetID: ERROR 403
I believe you are missing API in the url. This is from google spreadsheet api doc.
To acquire an API key:
Open the Credentials page in the API Console.
API keys: A request that does not provide an OAuth 2.0 token must send
an API key. The key identifies your project and provides API access,
quota, and reports.
The API supports several types of restrictions on API keys. If the API
key that you need doesn't already exist, then create an API key in the
Console by clicking Create credentials > API key. You can restrict the
key before using it in production by clicking Restrict key and
selecting one of the Restrictions. To keep your API keys secure,
follow the best practices for securely using API keys.
After you have an API key, your application can append the query
parameter key=yourAPIKey to all request URLs.
The API key is safe for embedding in URLs; it doesn't need any
encoding.
Google Spreadsheet Docs
You have to make sure to pass in the key=YOUR_API_KEY as the request parameter.
For example:
https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/Sheet1!A1:D5?key={YOUR_API_KEY}
In addition to #skamble89's answer, this 403 error is usually caused by incorrect or missed some configuration in Authorizing Requests. If you're authorizing requests with OAuth 2.0, make sure you use the proper scope with it.
Make sure you have a permission to call this spreadsheet and you enable the Sheets API in your developer console.
The Sheet must have a Public link for the API KEY to be used.
You have to share the spreadsheet, select "Get Link", and "Anyone with the Link".
That gives a link like this: https://docs.google.com/spreadsheets/d/1ShTP408LPzLOGjqXQTRcmXXXXXXXXXXXXXPUteQmY7o/edit?usp=sharing.
So there, the Sheet ID is after: /d/, is: 1ShTP408LPzLOGjqXQTRcmXXXXXXXXXXXXXPUteQmY7o.
curl "https://sheets.googleapis.com/v4/spreadsheets/1ShTP408LPzLOGjqXQTRcmXXXXXXXXXXXXXPUteQmY7o/values/A1%3AD3?key={YourApy"

Google v3 API and Oauth - Do I need to use the json file?

In the official docs for the Google API and OAuth, it has you download a .json file that includes things like clientid, secret, redirect etc. Then it has you build your Google Client like this (I'm using PHP and offline access to interface with the Youtube API):
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline"); // offline access
However, I've seen examples that allow you to define this information within PHP and set them on the object individually, instead of via the setAuthConfig .json file inclusion. In my case, that's what I want to do so I can have better control over my redirect url and allow storage of my clientid and secret within my settings forms/database. The examples I've seen look like this:
$client = new Google_Client();
$client->setClientId($clientid);
$client->setClientSecret($secret);
$client->setAccessType("offline");
$client->setRedirectUri($redirect);
Are both of these methods valid ways to define the Oauth Google Client in the current (v3) Google API and Oauth?

Name, Email from Google's OAuth API

I want to allow users to login with google on a site and collect their name and email address but I can't find any documentation on the userinfo scope for google's api: https://www.googleapis.com/auth/userinfo.
Thanks
This is a better way to get the name and email.
Set your scopes to:
https://www.googleapis.com/auth/userinfo.email
and
https://www.googleapis.com/auth/userinfo.profile
And use the endpoint:
https://www.googleapis.com/oauth2/v1/userinfo?alt=json
That will get you all you need!
I use
http://www-opensocial.googleusercontent.com/api/people/ and https://www.googleapis.com/auth/userinfo#email as the scope of the request tokens.
The protected resource url is
https://www-opensocial.googleusercontent.com/api/people/#me/#self to get the current user's data.
I get the user's G+ profile and name. I'm not able yet to get the user's email but I think i'm close
Retrieve OAuth userinfo using the Google Python API:
https://developers.google.com/api-client-library/python/start/installation
https://developers.google.com/api-client-library/python/guide/aaa_oauth
import httplib2
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
http = httplib2.Http()
http = credentials.authorize(http)
users_service = build('oauth2', 'v2', http=http)
user_document = users_service.userinfo().get().execute()
A client-side Javascript SDK for authenticating with OAuth2 (and OAuth1 with a oauth proxy) web services and querying their REST API's. HelloJS Standardizes paths and responses to common API's like Google Data Services, Facebook Graph and Windows Live Connect. Its modular so that list is growing. No more spaghetti code!
http://adodson.com/hello.js/
With the latest OAuth 2 draft support, Google provides Google ID tokens, an OpenID Connect implementation which - if you include the scopes https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email - will supply the email address (see the class GoogleIdToken in the latest Java API). Unfortunately, though, this doesn't provide the user's name. But it is a way that requires fewer roundtrips, if you can make do with just the email address.
Here is a php example using Google code how to get users details
....
$oauth2Service = new Google_Oauth2Service($client);
var_dump($oauth2Service->userinfo->get());
...
Bellow is the class from google
http://code.google.com/p/google-api-php-client/source/browse/trunk/src/contrib/Google_Oauth2Service.php

Resources