Can we enable 'Sign in with Google' for Google Identity Platform multi-tenants programmatically? - google-signin

As a B2B SaaS provider, we currently create and manage tenants from Google Identity Platform. As we expect to grow, we would like to automate the tenant creation flow with Sign in with Google.
However, I found that Identity Platform Admin SDK doesn't support social sign-in method(including Google), only available using the Cloud console.1
Is there any programmatic way to enable Sign in with Google for multi-tenancy environment?
We expect to provide different sign in page for each tenant as they might need own branding.
Given new Google Identity Services APIs just announced, other solutions also welcome. Thanks!
Reference :[Managing Identity Platform tenants programmatically document]
Table shows what sign-in methods you can configure using the Admin SDK and the Cloud Console in a tenant-specific context:

Take a look at using an intermediate iframe, specifically the section entitled One Tap Displaying Domains. It seems like it may help out here.
Now, if you're trying to individually brand the application name and logo which is displayed on the OAuth consent screen for each tenant you'll need to create, and verify a separate project for each tenant/domain. OAuth brand verification is not a process suitable for automation.
In summary if you'll need to tightly control the branding you'll create a project, get if verified and your tenant will have a custom name and logo. Otherwise, you should be able to quickly onboard and support multiple domains using an intermediate iframe.

We've implemented it so you can try our code and do it also.
This is an example to enable Google SSO for a specific tenant
gcp_project = YOUR_PROJECT_ID
google_client_id = YOUR_GOOGLE_CLIENT_ID
google_client_secret = YOUR_GOOGLE_CLIENT_SECRET
def enable_google_idp(self, tenant_id: str):
"""
Enables the Google SSO for a tenant
:param tenant_id: the id of the tenant
"""
app = firebase_admin.initialize_app()
tenant_url = f"projects/{gcp_project}/tenants/{tenant_id}"
url = f"https://identitytoolkit.googleapis.com/v2/{location}/defaultSupportedIdpConfigs?idpId=google.com&key={api_key}"
payload = {
"clientId": google_client_id,
"clientSecret": google_client_secret,
"enabled": True,
"name": f"projects/{gcp_project}/defaultSupportedIdpConfigs/google.com"
}
authenticated_session = google.auth.transport.requests.AuthorizedSession(app.credential.get_credential())
resp = authenticated_session.post(url=url, json=payload)
# raise if something failed
resp.raise_for_status()
return True

Related

How Does Firebase Analytics count New Users in Web App

We have a web app that users log into using Firebase Auth. According to our the authentication section of our firebase console, we have 690 user that have created accounts, and we believe that is correct.
According to our Firebase Analytics console, we have 2,100 new users in the past 90 days. I think I understand that Firebase Analytics tracks users with a device ID (?). So, if this were a iOS app, an uninstall and install would trigger a a new user counted in analytics. But, how does this work on a web app? Cookie? Some kind of browser id? A session?
So, I think if we want to track unique users accurately, we would use the set the user id, with this:
https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics#setuserid
Which according to the docs linked above, 'Use gtag 'config' command to set 'user_id'. So it does this: https://developers.google.com/analytics/devguides/collection/gtagjs/cookies-user-id#set_user_id
Which allows the users to be tracked across sessions. Therefore, users should not double count.
Notice that the setUserId section in the firebase analytics docs does not have a web section (although the setUserID function does exist in the javascript sdk as shown tow links above) https://firebase.google.com/docs/analytics/userid
So... would it then work to get the user id (uid) when they log in (https://firebase.google.com/docs/reference/js/firebase.User). And then use the setUserId method to set the id?
It's unclear because the documentation does not seem to be in one source. I am just trying to put it all together
You are correct that you can use the setUserId API (across iOS, web and Android) in order to identify the same user across platforms. Note that you'll need to:
Set the default reporting identity to "By User-ID then Device" in the Reporting settings for Google Analytics in the Firebase console (see attached screenshot and docs for more info).
Make sure you are following the Privacy Policy when using the User ID.

Accessing Google analytics api using api key

I'm trying to implement Google analytics API using API key to make it available without authorization. But i can get examples using CLIENT ID in google developer console itself. Can anyone help me with an example using api key?
It is not possible to access Google Analytics API with the API key. You must use Open Authentication.
If you are trying to access your own data you can use a service account. Create new credentials choose Service Account.
You can then take the service account email address:
1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com
Add it as a user at the ACCOUNT level it is very important that it be at the ACCOUNT level it wont work other wise. Your application with then be able to access your Google Analytics data with out a log in.
Without knowing what language you are working with I cant give you any examples.
Update:
If as you say you are planning on doing this with JavaScript then you will have to go with Oauth2 and request access. There is no way to use a Service account with JavaScript.
There for I strongly recommend that you find a server sided programing language to do this in. Even if it did work with JavaScript you would end up running out of quota on the API before to long.
Google Analytics' EmbedAPI will allow you to display your Google Analytics via javascript, and users will be able to log in on page.
You will still need to get your clientAPI, but then users will be able to login independently.
The javascript code is described in the dev guide and a sample is below:
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'Insert your client ID here';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
});
</script>
The API limit should be no problem, its 50,000 calls per day.

Google Analytics - Access custom segments through Service Account

My application needs to fetch Google Analytics data from backend servers.
I am using Google Service Account in my application.
Though I have given all permissions to my service account through Google Developer console, it turns out that my service account cannot access custom segments of my user account.
A way could have been to copy these segments from user account to service account, but there seems like no way to login via service account and be able to copy segments from user account to service account.
So, there seems like no way to be able to fetch custom segments in a web application from backend...
Is there any way to do so?
Can any other account(web application, Installed application account) serve my purpose?
Reading the documentation of above two Google accounts reveals that user would be prompted for authentication (at least once) during authorization in these 2 accounts which is not feasible in backend servers.
I found a similar thread for my query Google Analytics V3 - How to create custom segments for API Service Accounts , but user in this thread resorted to not using segments at all, but I do need to use them in my account.
PS: I am writing my application in RubyOnRails and would be using Ruby Gem for Google Authentication
Answer: No there is no way to add segments to the Service account. Even the Mangment api only allows you to list segments not add them. Segment Management API documentation
An Idea: You could us normal Oauth2 Authenticate it using your account, Save the refresh token someplace and use that in your application to see the data. Then it would be like the Application is always you and would be able to see your segments.
Sorry I don't know ruby so I cant help you with getting the idea working.

Google Analytics API: "User does not have sufficient permissions for this account."

I'm writing a Ruby app that accesses the Google Analytics API to pull down some experiment information.
The app connects and authenticates using a Google Service Account via the following function:
def connect
...
##client = Google::APIClient.new(:application_name => 'My Service App',
:application_version => '1.0.0')
key_file = Rails.root.join('config', 'privatekey.p12').to_s
key_secret = 'somesecret'
key = Google::APIClient::PKCS12.load_key(key_file, key_secret)
asserter = Google::APIClient::JWTAsserter.new(
SECRETS[:google_service_account_email],
['https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/analytics.readonly'
],
key
)
##client.authorization = asserter.authorize()
...
end
...which authenticates and discovers both APIs without issue.
Using the client against the YouTube Analytics API works without issue. Using the same exact account to access the Analytics API via...
response = ##client.execute({
# 'analytics is the API object retrieved via discover_api()
:api_method => analytics.management.experiments.list,
:parameters => {
'accountId' => 'AAAAAAAA',
'profileId' => 'PPPPPPPP',
'webPropertyId' => 'UA-WWWWWWWW-#'
}
})
Results in a 403 error response:
{"domain":"global","reason":"insufficientPermissions","message":"User does not have sufficient permissions for this account."}
In regards to authorization, I have double-checked the account service#myapp.com:
Has full permissions to the Google Analytics web interface. I logged in using the service#myapp.com account and was able to view the same Experiments I attempted to list.
Has enabled the Analytics API. Within the API Console, I confirmed in the Services section that the Analytics API item is switch to ON. (Just like YouTube Analytics is.)
I am using the appropriate AccountID, ProfileID, and WebPropertyID values. Copied directly from the Google Analytics web interface.
Given that the service account can access at least one API (YouTube Analytics), and the associated account (service#myapp.com) can access the Analytics web interface, there seems to be something wrong with the service account accessing the Analytics API in particular.
Any ideas?
Similar topics:
“Not sufficient permissions” google analytics API service account (NOTE: This error is slightly different than mine)
Analytics blog post, check comments section for 'permissions'
Make sure you give the service account email (something like 1234567890#developer.gserviceaccount.com) permissions to read/write from your GA view.
Admin > View > User Management > "Add permissions for:"
Pick the right id!
In my case I was using the right credentials (account id, account secret -> authorization_code -> access_token) AND had the email permissions set up right but I was using the account id on the Admin > Account settings page and simply adding ga: to the front.
The id you actually need is the table id! (or that's the one that worked for me at least since most people here are mentioning the account id, which didn't work for me.). You can find that one here: https://ga-dev-tools.appspot.com/account-explorer/
And then you can query as
service.get_ga_data(TABLE_ID,'2017-03-25','2017-03-25','ga:users,ga:pageviews')
I found this API to be badly documented overall and the UI was unclear. But maybe that's just me.
If you still see this message after you added your developer email to analytic user.
You may need to add scope to the object, before new Google_Service_Analytics($client);
$client->setScopes("https://www.googleapis.com/auth/plus.login");
I spent whole day trying to solve this!
I also had to go to the developer console and enable the API in order to make it work. Go to the developer console and select your project and enable the API(s) you want to use.
Make sure your are entering the correct table_id
(ie. GetProfiles(oauth_token)
tableid_input = "ga:72848696")
Even after adding the email to the account level in analytics I still had the same permission problem but the following suggestion helped but didn't solve it:
$client->setScopes("https://www.googleapis.com/auth/plus.login");
That didn't work for me but this did:
$client->setScopes("https://www.googleapis.com/auth/analytics");
https:// is now required to authenticate.
If you are new just to let you know 3 Step procedure required
Enable Google Analytics Reporting API then create service email account (OAuth Client ID)
Add and give permission this service email in google console
Add and give permission this service email account in Google analytics tracking -> User management
Make sure you give the service account email (something like 1234567890#developer.gserviceaccount.com) permissions to read/write from your GA view.
Admin > View > User Management > "Add permissions for:"
I got this issue when I try to integrate GA source to metabase.
Metabase requires Oauth clientid and secret. So I create Oauth clientid in GA (If you face an issue which said you need a Guite user to make it internal access, then you need register a new account under workspace).
Then, I solve this issue by adding my google cloud(workspace) account to view user management, not
1234567890#developer.gserviceaccount.com
Just the google cloud login account, I tried with 1234567890#developer.gserviceaccount.com but it doesn't work. The difference for metabase is it ask the oauth id and secret for your google cloud account not service account.
Hope this can help someone face the same situation.
But it is still trick because another GA4 service which don't have any view
How to create view in Google Analytics 4
Still can't solve this issue.
If any one knows it, please comment. Just don't know how to call the api in GA4 since there isn't view at all.
For me, it has been solved when I select the property that was created with enabling "Create a Universal Analytics property" in "Show Advanced Options" section
Other answers are outdated for Google Analytics v4.
There's a different api that one need to enable and use.
https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries
For node.js:
import { BetaAnalyticsDataClient } from "#google-analytics/data";
import { google } from "googleapis";
const auth = new google.auth.GoogleAuth({
credentials: {
client_email: process.env.GOOGLE_CLIENT_EMAIL,
client_id: process.env.GOOGLE_CLIENT_ID,
private_key: process.env.GOOGLE_PRIVATE_KEY,
},
});
const analyticsDataClient = new BetaAnalyticsDataClient({
auth,
});
If someone has more view he should use the view ID.

How to write to our own calendar via the Google Calendar API (v3)

I need to write to a Google Calendar from data in our datastore (App Engine app).
I want to access via OAuth 2.
Reading is no problem - the calendar is public and I just use the simple API access method.
Writing is a "problem" - obviously I need to authenticate. However, the calendar is owned by the app administrators, and we want to write to the calendar as a background task - no user interaction is required.
I have gone through all Google's documentation, but I feel none the wiser - how can I do a one -time setup for permanent write access to a Google Calendar, via the V3 API?
To make calls on behalf of your App Engine app without user interaction you should make use of the App Identity module:
https://developers.google.com/appengine/docs/python/appidentity/
If you are using the Google API Client Libraries, using the AppAssertionCredentials object will do this automatically for you:
https://developers.google.com/api-client-library/python/guide/google_app_engine#ServiceAccounts
Note the following:
You will probably still need to supply the simple key in order to attribute quota usage to the right project.
The App Identity module won't work during local App Engine development - you will need to deploy into production in order to obtain valid credentials.
You will need to share the calendar you are writing to with the email address associated with the service account for the App Engine app. To find this email address go to the App Engine Administration Console -> "Application settings" and look for the service account email.
Finally, I'm not 100% sure that the Calendar API allows service accounts direct access, but you should give this a try. If that doesn't work for you an alternative may be to generate a refresh token for a real user that has access to the calendar, and look at embedding that into your application - the service account method is preferable, so I would try that first.

Resources