retrieve all events within a domain using Google Calendar API - google-calendar-api

I'm trying to retrieve all the events programmed within a domain entreprise.tn using Google Calendar API.
On google admin console, I create a new project and a new service account with owner role as described by that thread.
I enabled Google Calendar API and Admin SDK like described by that thread.
the list of scopes added on Admin console>Security are :
https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group, https://www.googleapis.com/auth/admin.directory.resource.calendar, https://www.googleapis.com/auth/calendar.events.readonly, https://www.googleapis.com/auth/calendar.readonly
My code is:
Calendar service = getCalendarService();
List<Event> items = new ArrayList<Event>();
String pageToken = null;
do
{
Events events = service.events().list("service-account-esp1#my-first-project-274515.iam.gserviceaccount.com").setPageToken(pageToken).execute();
items = events.getItems();
for (Event event : items)
{
System.out.println(event.getSummary());
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
if (items.isEmpty())
{
System.out.println("Empty");
}
else
{
System.out.println("Exists");
}
the file my-first-project-274515-361633451f1c.json is the generated file when creating the service account and performing G Suite Domain-Wide Delegation of Authority.
the service-account-esp1#my-first-project-274515.iam.gserviceaccount.com is the client email
It looks ok, all the required configurations are done.
How evere, I got that exception:
avr. 18, 2020 12:28:59 PM
com.google.api.client.util.store.FileDataStoreFactory
setPermissionsToOwnerOnly AVERTISSEMENT: Unable to set permissions for
C:\Users\Administrateur\credentials, because you are running on a
non-POSIX file system. Charge Calendars: Sat Apr 18 12:28:59 BST 2020
a Exception in thread "main" java.lang.IllegalArgumentException at
com.google.common.base.Preconditions.checkArgument(Preconditions.java:128)
at
com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:35)
at
com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at
com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.(GoogleAuthorizationCodeFlow.java:197)
at
tn.esprit.spring.google.calendar.Service.getCredentials(Service.java:75)
at
tn.esprit.spring.google.calendar.Service.getCalendarService(Service.java:90)
at tn.esprit.spring.google.calendar.Service.main(Test.java:102)
it's blocked on GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Could you please tell me what I missed ?.
Thanks in advance.

You should use mail user instead:
Events events = service.events().list(user#entreprise.tn)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
HTH

Related

Azure AD Application Add User to Active Directory using Client Credentials

I am trying to add a user to an application Active Directory but with little success. I am using the GraphServiceClient with.Net Core
The documentation here says I need these permissions
Azure AD Graph Client Beta Docs
Application Directory.ReadWrite.All
But I cannot find where in the Azure Portal I can assign this permission.
The code is above, the GraphServiceClient is in beta at the moment and this is not part of the API yet, so I am calling the request manually.
Below is my code for authentication, I am using my applications client secret which is set against the application in the AD. I can read directory data fine.
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
try
{
if (null == _configuration)
{
throw new InvalidOperationException("Azure AD Configuration is not set");
}
var authContext = new AuthenticationContext(
$"{_configuration.Instance}/{_configuration.Domain}", false);
var credentials = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
var authResult =
await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
}
catch (Exception ex)
{
_logger.Error("Authentication Provider, unable to get token", ex);
}
}
Update - After checking with Rohit's advice, you can see I have the permissions set. But notice they are all in blue with the ticks next to them! I have changed and saved, you can see the save button is disabled. I have clicked Grant Permissions. Is this relevant?
But I cannot find where in the Azure Portal I can assign this
permission.
In Azure portal navigate to Azure Active Directory > App Registrations > Your specific app > Settings > Required Permissions
Click on Add and Select Microsoft Graph
Now, in the Application Permissions section, check "Read and write directory data"
Once you're done, do "Grant Permissions" for Admin consent, as this permission needs it.

how to fix 403 error in google authentication at xamarin forms for accessing web resources at Android app

thanks in advance.....
i got this error while connecting to my app with azure cloud via google authentication
"403. that's an error. error: disallowed _useragent this user- agent is not permitted to make on oauth authorization request to google as it is calssified as an embedded user- agent per our policy ,only browsers are permitted to make authorization request to google. we offer several libraries and samples for native apps to perform authorization request in the browser."
how to fix this error.....
This happens from last year because of a change in Google's security policy. The work around is to use Xamarin.Auth and use Interceptors in the native codes to catch the Authentication process. A good example is available in this following link Xamarin Authentication
class ActivityCustomUrlSchemeInterceptor : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
/* global::Android.Net.Uri uri_android = Intent.Data;
//#if DEBUG
// System.Text.StringBuilder sb = new System.Text.StringBuilder();
// sb.AppendLine("ActivityCustomUrlSchemeInterceptor.OnCreate()");
// sb.Append(" uri_android = ").AppendLine(uri_android.ToString());
// System.Diagnostics.Debug.WriteLine(sb.ToString());
//#endif
// Convert iOS NSUrl to C#/netxf/BCL System.Uri - common API
Uri uri_netfx = new Uri(uri_android.ToString());
// load redirect_url Page
AuthenticationState.Authenticator.OnPageLoading(uri_netfx);*/
var uri = new Uri(Intent.Data.ToString());
// Load redirectUrl page
AuthenticationState.Authenticator.OnPageLoading(uri);
this.Finish();
return;
}
}

Give Google Service Account access to all my Google Analytics Accounts

My work email has access to around 100 analytic accounts. Is there anyway give a google service account to all of the analytics I have access to with out needing to manually add it to every account?
Working off of Eike's comment, it seems to be possible from Google Apps Scripts:
function listAccounts() {
var accounts = Analytics.Management.Accounts.list();
if (accounts.items && accounts.items.length) {
for (var i = 0; i < accounts.items.length; i++) {
var account = accounts.items[i];
var body =
{
permissions:
{
local: ['READ_AND_ANALYZE'] //or whatever permissions you need
},
userRef:
{
email: 'theemailaddressyouneed'
}
};
Analytics.Management.AccountUserLinks.insert(body, account.id);
}
} else {
Logger.log('No accounts found.');
}
}
You will have to add the "Advanced Google Service" resource: Google Analytics API.
When you run it, you will also need to allow as a user who actually has permissions to add users to GA accounts.
Edit: I forgot to add, this seemed to create a new project for me in the developer console. I got an error message the first time about the project not having the API enabled. Click details or go to the dev console and find this project and enable the Google Analytics API.

Creator does not receive notification email about attendee response status in google calendar api

I am using service account to authenticate google calendar.
There is one admin (organizer) for my application and multiple users (creators) who creates event on behalf of admin and invitation email goes to attendees as well as organizer about event creation. But the issue is, there is intimation to creator about the response status of the attendee.
organizer(abc#gmail.com) receives the response status email of (acceptance or declined) of an attendee but creator(xyz#gmail.com) doesn't not receive my email.
/*adding organizer data */
Event.OrganizerData org = new Event.OrganizerData();
org.Email = gm.Organizer; //abc#gmail.com
eventEntry.Organizer = org;
/*adding creator data */
Event.CreatorData creator = new Event.CreatorData();
creator.Email = gm.CreatedBy; //xyz#gmail.com
eventEntry.Creator = creator;
/*inserting an event to service account calendar*/
var request = er.Insert(eventEntry, calID);
request.SendNotifications = true;
var re = request.Execute();
how do I achieve this requirement. I did lot of researching on internet but did not find any answer.
I know it's late though.
SendNotifications is deprecated now. Use SendUpdates method. See the official doc here

Service account authentication

I'm trying to create calendar event via PHP for one particular user - say developement#example.com.
I've created Service Account in Google Developers Console, got ClientID, E-mail address and private key. The authentication is done with code:
$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$cred = new Google_Auth_AssertionCredentials(
'somelongstring#developer.gserviceaccount.com.',
array('https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.readonly'),
file_get_contents('p12 file'));
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
This type of authentication seems pretty OK. But all events are created as user with E-mail address somelongstring#developer.gserviceaccount.com instead of developement#example.com.
I've tried setting sub parameter:
$cred = new Google_Auth_AssertionCredentials(
....
$cred->sub = 'developement#example.com';
$client->setAssertionCredentials($cred);
But this piece of code throws exception:
Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }'
And now I'm lost. Any advice?
OK, resolved ;-)
Problem was with developement on own domain.
As mentioned in other question and in Google SDK Guide I have to grant access for service account to all scopes I request access. I forgot to add read-only scope.

Resources