Analytics API : automatic authentification - php

I'm trying to build a dashboard using Google Analytics Reporting API, in order to create reports for my company's clients.
The problem is that I need to create reports using a cronjob, but this requires an authentication. I tried the following approaches :
1. Using the API for web applications :
I managed to make this work, but the OAuth2 process forces me to authenticate into Google by redirecting me to the Google login page. Once logged in, the token is created and my report is generated. But I couldn't find a way to authenticate automatically without a user intervention (i.e. filling the Google login form)
2. Using the API for service accounts :
With this solution, I am able to create reports without manually logging into Google, which is awesome. But this method requires me to add the service account to the Google Analytics account, by adding the newly created user XXXXXXXX#PROJECT-ID.iam.gserviceaccount.com to each of the Google Analytics view I wish to access. I can't do that, as some of the views I'm trying to access are managed by my company's clients and I can't ask each of them to add yet another Analytics user.
I need to be able to access the Analytics views using the user e-mail already configured. I tried to add this address as the owner of my service account in the Service Accounts Manager, but no luck (see screenshots hereafter).
Is there any way I can either use the API for web applications with a static token (i.e. without having to manually log into Google), or use the API for service accounts without having to add the Google-created user in each of my Analytics views ?
I'm at a loss here, so any advice will help.

Due to the fact that you don't have control of all of the accounts as you said you wont be able to use a service account.
There for you will have to use Oauth2. Someone will have to authenticate your application the first time. Once access has been granted the first time you will be given an access token to access the API and a refresh token. If you store this refresh token you will then be able to request a new access token from your cron job when ever you like in order to run your reports.
The trick is saving the refresh token associated with each users account. Your clients will have to authenticate the application to grant you access. You store the refresh token. The refresh token shouldn't expire (there are a few reasons why one might) you will be able to gain access when ever needed.
Note: You can also place the service account email at the account level will give you access to everything. But this wont help you with clients you don't have access to.
Update:
Refresh tokens will not expire except under:
A refresh token not used for 6 months will also expire.
users can go to App settings on there google account and revoke your access at anytime.
A user can re-authenticate your application (same client id) 26 times giving you 26 different refresh tokens, after number 26 the first refresh token will expire. You can only have 26 working refresh tokens for a single user. Make sure you always save the newest refresh token.

As far as I know, the intended method for cron jobs is to use API for service accounts, just as you have described. However, it seems to be an expected and appropriate behavior, that you cannot access a random view just by providing its ID with your service account, without prior authorization from the owner of the view. Without this settings, Analytics will not know about your relationship to your client, and therefore refuse access to data.
I'm not sure, if it is supported, but you could try to add your service account on property or Analytics account level, so that all connected views inherit this setting.

Related

Central OAuth2.0 Authorization on the Backend-Side using PHP and curl for Spotify Web API

I am creating an application which aims at automatically creating Spotify Playlists in a central Spotify account (not the account of the end users).
I have set up this account and created the developer app for the secret and the client_id.
On the backend side, I am using PHP to authorize this central user, and it is working as long as I am logged in myself with that account.
Users that visit my website should be able to create playlists via that interface through the Spotify Web API without the need to authorize their account nor being logged in at all.
If I'm trying to open the same page on a separate device (without having any account logged in), it just gives me the following error:
User not registered in the Developer Dashboard
Is it somehow possible to perform this authorization process only on the backend side without the need for the user to authorize it?
Eventually, I want to send the playlist URL created in the central Spotify Account to the user who can open it in their own app or share with others, if they want to.
I try to avoid that multiple users must authorize for my app, since I don't need to access personal information from their account, anyways.
I used the 3-step process for authorization as described in this Stackoverflow Post: Spotify oauth2 with PHP curl. How to get authorization code?
If necessary, I will provide more information.
Do you have any idea, how I can implement this authorization process for the single account on the backend side, without the user even showing any authorization process of the Spotify Web API at all?
EDIT1: I am not trying to login on the behalf of my users, just automatically for my own account without the interactive login with Spotify. Is that even possible?
I received valuable feedback from the Spotify Developer Community that helped me finding a solution to the problem.
When you let the central Spotify account login to your app, you'll [get] an access_token (that will expire in 1 hour) and a refresh_token.
When the access_token of that account expires, let your server send a POST request to the Accounts service /api/token endpoint, but use the refresh_token in place of the access_token.
A new access_token will be returned.
A new refresh_token might be returned too. (I don't think that's even needed)
You can read more about it here.

Revoke access of microsoft/outlook account using outlook or graph rest API

I'm using Microsoft Graph API for integration of microsoft/outlook calendar in my app.
API reference is here
I want to revoke user's access of their calendars from my app but didn't find any way to do so. I tried with following api but no luck:
DELETE https://graph.microsoft.com/v1.0/users/{user_id}
Well, that command would delete the user entirely. So while that would certainly remove them from the calendar, I'm guessing this isn't the outcome you're looking for. :-)
If you're looking to remove the permission for your app, there are a couple of ways to trigger this:
Simply stop requesting that user's calendars from your app. This won't revoke permission to the calendar however so this likely isn't sufficient.
Drop Calendars.Read and Calendars.ReadWrie from your list of requested scopes.
In order to ensure this change is reflected in the user's account, you'll need to re-authenticate the user with the query param prompt=consent auth URI.
Have the user revoke permission for your application entirely. This is done by visiting https://myapps.microsoft.com.
There are certain apps that a user cannot directly revoke. These are apps who were granted access at the organization level. To revoke these, an Administrator will need to do this in the Azure Portal.

Choosing the right OAuth2 grant type for PHP web app

I'm building a very typical web app product. It will likely have corresponding mobile apps in the future. I'm building it from the ground up with a REST API, which is secured using OAuth2. I've got OAuth2 working, and I'm able to connect successfully using various grant types.
What I'm a little confused about is what grant types to use for the actual web app. Here's what I had in mind:
Public API access
Before a user logs into the web app, some API access is required for things like user registration and password resets. I was thinking of using the client_credientials grant type. A simple client id and secret validation in return for an access token.
However, it seems totally unnecessary to request an access to token for every single public request or even for each session. It seems to make more sense to just generate ONE access token that my web app will always use.
Yet, this seems to go against how OAuth is designed to work. For example, access tokens expire. What is the right way of doing this?
Private user API access
Next, for a user to login to the web app I was planning on using the password grant type (resource owner password credentials). This approach allows me to save the user_id with the access token—so I know which user is logged in. Further, by using scopes I can restrict access within the API.
I plan to save the access token within the PHP session. As long as the PHP session is active they will remain logged into the web app.
Is this an appropriate design for user login?
For Public API Access:
One method is to skip tokens all together and just use Basic HTTP Authentication for API access. You could accept Client Credentials for this, and limit what clients can do using client-specific scopes. Github offers HTTP Basic authentication using user credentials for all their API calls.
For Private user API Access:
This is an interesting question because it begins to breech the line between Authentication and Authorization. OAuth is used for Authorization, so logging in users becomes dicy. Session management, for example, is something not covered by the OAuth2.0 spec.
However, this is a common use of OAuth2.0 anyway. You can use the password grant type, or any other grant type for that matter, to obtain an access token. A major downside is they have to trust your application with their password (Not a big deal for your own app, but for 3rd parties not so much). Also, being logged in one place does not necessarily mean being logged in somewhere else (rather than SSO, you have "linked accounts", so the sessions are managed separately). One way around this is to ALWAYS send users to the oauth authorize endpoint, and if their session is active on the OAuth2.0 Provider side, reroute them back to the client app with an access token or authorization code. This way, if the session is active with the OAuth2.0 provider, the client can immediately log them in.

Google Apps SSO + Get Users in Google Apps Domain

I have recently implemented the SSO functionality for a Google Apps Marketplace app we are developing. In simple words: it provides a way to retrieve the Google Apps' user's email and log him in in your website, without the need of authorization on his end. You just need the consumer key and consumer secret, provided by Google to the app during installation on your domain (the installing user also authorizes (a one time action) any other permissions you request in the Manifest file).
Now I have somehow managed to get the SSO user login working using JanRain's OpenID PHP library and adding Google Apps as provider using the PHP Extensions for Google Apps OpenID Discovery.
However, after logging in, I need to implement a functionality that will retrieve all users in a given Google Apps domain. I've already did that using oAuth2 authentication and the following Directory API. However, this requires the existense of a consumer key, consumer secret and a redirect URL (that must be registered in the Google API console).
Is there a way to remove this convenience and instead allow our users to directly be able to get their Google Apps domain's users, using the existing SSO authentication we made in the background while logging him in? Otherwise, it will be too much hassle for the user to register the app at the Google API console, enter the correct redirect URL and set it up in our website and then he will be able to get his domain's users.
Regular users cannot use the Directory API, you'll need to authenticate as an admin user to make Directory API calls.
Depending on your needs though for accessing all users, you may be able to get by with requesting access to the user's Contacts scope and grabbing a copy of the full Global Address List which contains information on all non-hidden domain users as well as non-hidden groups and shared contacts.

How to prevent prompt for 'Allow Access' each time when using google service in same application by same google account

I'm using OAuth 2.0 Google API for google calendar service authentication. Each time when a users logs in the application, it prompts for Allow access even if the user has already allowed access on previous visits to the application.
How can I code it so that it remember the application and user for allowed access by users in past and so do not prompt for "Allow access" again for that same application.
I assume you are using Google PHP API. Setting client object to use auto for approval promt does the trick for me.
$client = new apiClient();
$client->setApprovalPrompt('auto');
When making the OAuth request make sure your "access_type" request:
"access_type" : "offline"
This means the user gives you offline access, and you can continue to make requests with their account.
Using offline also means you'll receive a "refresh_token". Once your access has expired, your application can automatically trade in the "refresh_token" for continued access, without the client having to "allow" again.
$client->revokeToken($accessToken);
If you are using this line somewhere then removing it might help.
Basically what I've figured out is that if the access token is revoked prior to it's expiration, google takes it as an act to reset the permissions as well.
I might be wrong, but I've have not come across a better conclusion yet.

Categories