Google Calendar API C# credentials throw an exception - c#

I'm following this tutorial: https://developers.google.com/google-apps/calendar/instantiate
My code:
public static void Main()
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets()
{
ClientId = "actualclientid",
ClientSecret = "actualclientsecret"
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
The issue is, this part of the code throws me an exception:
{"Could not load file or assembly
'Microsoft.Threading.Tasks.Extensions.Desktop, Version=1.0.16.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
dependencies. The system cannot find the file
specified.":"Microsoft.Threading.Tasks.Extensions.Desktop,
Version=1.0.16.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}
PS.: While most likely irrelevant to the issue, when setting up my project on google to get the credentials, I've selected Installed Application -> Other (As I'm assuming that's what a console application is)
EDIT: Adding https://www.nuget.org/packages/Microsoft.Bcl.Async/1.0.166-beta seems to have solved that issue. Now the remained of my code:
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Test"
});
var x = service.Events.List("actualcalendarid").OauthToken;
Console.WriteLine(x);
Console.ReadLine();
returns an empty line, even though when I run the application it does request access to my calendar and such. Am I forgetting something?

Make sure you have added all the references to your project.
The following need to be installed using NuGet
-Install-Package Google.Apis.Calendar.v3 –Pre
-Install-Package Google.Apis -Pre
-Install-Package DotNetOpenAuth -Version 4.3.4.13329
-Install-Package Google.Apis.Auth.Mvc -Pre
And add reference Microsoft.Threading.Tasks.Extensions to your project.
EDIT:
You don't retrieve data because you are not executing your query.
var result = service.Events.List("primary").Execute();
private async Task<UserCredential> GetCredential()
{
UserCredential credential = null;
try
{
using(var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { CalendarService.Scope.Calendar },
"user", CancellationToken.None, new FileDataStore(""));
}
}
catch (IOException ioe)
{
Debug.WriteLine("IOException" + ioe.Message);
}
catch (Exception ex)
{
Debug.WriteLine("Exception" + ex);
}
return credential;
}
private CalendarService GetCalenderService(UserCredential credential)
{
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Sample"
});
return service;
}
private Events GetEvent(string CalendarId)
{
var query = this.Service.Events.List(CalendarId);
query.ShowDeleted = false;
query.SingleEvents = true;
return query.Execute();
}

Related

Google Drive API Files.List() Error invalid_grant Bad Request

I am using Google Apis Drive v3 with a simple request to find a folder with a specific ID and then to list all of the files in the folder.
However on request Execute it is creating the exception:
“Error: invalid_grant, Description: Bad Request, Uri:”
It used to work but has stopped sometime in the last month approx. while I was working on another project.
I have checked the API console and our Client ID is registered (I have hashed out the ID, Secret & refresh token) and everything seems OK with the creation of a service it is sending the request that is not working.
However the query used to work and I have tried changing the query and it still does not work.
Code is below, any suggestions on how to resolve this would be appreciated. Thanks
Request File List
List<File> fileList = new List<File>();
List<File> FileList_Lst_Ordered = new List<File>();
try
{
string pageToken = null;
do
{
request.Q = "'" + folderId + "' in parents";
//request.Q = String.Format("name='{0}'", "Release Scripts Folder");
//request.Q = "mimeType = 'application/vnd.google-apps.folder' + title='" + folderId +"'";
request.Spaces = "drive";
request.Fields = "nextPageToken, files(id, name, mimeType, trashed)";
request.PageToken = pageToken;
var result = request.Execute();
// Iterate through files
foreach (File file in result.Files)
{
// If it is a matching type (or we are retreiving all files)
if (!(bool)file.Trashed && (file.MimeType == type || type == "ALL"))
{
fileList.Add(file);
}
//RST_00001
else if (!(bool)file.Trashed && (file.MimeType == "sql" || file.MimeType == "text/x-sql"))
{
fileList.Add(file);
}
}
// Increment file token
pageToken = result.NextPageToken;
} while (pageToken != null);
//RST_00002: Order List Alphabetically
int Counter_int = fileList.Count();
for (int i = 1; i <= Counter_int; i++)
{
FileList_Lst_Ordered.Add(fileList.OrderBy(x => x.Name).FirstOrDefault());
fileList.Remove(fileList.OrderBy(x => x.Name).FirstOrDefault());
}
}
catch (Exception Ex)
{
errorString = Ex.Message;
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Error Occured While Obtaining script list for folder " + folderId + ", full error: " + Ex.ToString());
}
Initialise Service In GoogUtils.cs Helper
public static DriveService InitService(ref string errorString)
{
try {
var token = new TokenResponse { RefreshToken = "###" };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "###",
ClientSecret = "###"
}
}),
"user",
token);
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = ApplicationName,
});
return service;
}
catch (Exception e)
{
errorString = e.Message;
}
return null;
}
I have been able to resolve the problem. By re-writing the service so it uses GoogleWebAuthorizationBroker.AuthorizeAsync instead of GoogleAuthorizationCodeFlow, I also am now loading the credentials from a JSON. See blow.
Thanks to all for your contributions and help:
public static DriveService InitService(ref string errorString, string Log_Filename)
{
try
{
string[] Scopes = { DriveService.Scope.DriveReadonly };
UserCredential credential;
if (!System.IO.File.Exists(credential_json))
{
System.Windows.Forms.MessageBox.Show("Unable to Initialise Google Drives Service credentials not found.");
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Unable to Initialise Google Drives Service credentials not found.");
}
using (var stream = new FileStream(credential_json, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
if (credential.UserId == "user")
{
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Credentials file saved to: " + credPath);
}
else {
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Unable to verify credentials.");
return null;
}
}
// Create Drive API service
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Validate Service
if (service.Name == "drive" && service.ApplicationName == ApplicationName)
{
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Google Service Created.");
}
else
{
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Unable to create service.");
return null;
}
return service;
}
catch (Exception Ex)
{
System.Windows.Forms.MessageBox.Show("An Error Occured While Initialising Google Drives Service");
System.Windows.Forms.Clipboard.SetText(Ex.ToString());
Helpers.Helpers_TextFile.TextFile_WriteTo(Log_Filename, "Google Drive Init - Error Occurred: " + Ex.ToString());
errorString = Ex.Message;
}
return null;
}

Google Calendar API for UWP Windows 10 Application One or more errors occurred

I'm trying to use Google Calendar API v3, but i have problems while running the codes, it always gives me that error :
An exception of type 'System.AggregateException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: One or more errors occurred.
I don't know why it does, also It should work as well. Here is a screenshot for it :
Also my codes are :
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
Scopes,
"user",
CancellationToken.None).Result;
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var calendarService = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Windows 10 Calendar sample"
});
var calendarListResource = await calendarService.CalendarList.List().ExecuteAsync();
If you can at least help with calling it through REST API, that would be great too, but you must consider that it's UWP, so it has another way to get it work as well.
As i already tried through REST API, but i always get "Request error code 400".
Thanks for your attention.
The Google API Client Library for .NET does not support UWP by now. So we can't use Google.Apis.Calendar.v3 Client Library in UWP apps now. For more info, please see the similar question: Universal Windows Platform App with google calendar.
To use Google Calendar API in UWP, we can call it through REST API. To use the REST API, we need to authorize requests first. For how to authorize requests, please see Authorizing Requests to the Google Calendar API and Using OAuth 2.0 for Mobile and Desktop Applications.
After we have the access token, we can call Calendar API like following:
var clientId = "{Your Client Id}";
var redirectURI = "pw.oauth2:/oauth2redirect";
var scope = "https://www.googleapis.com/auth/calendar.readonly";
var SpotifyUrl = $"https://accounts.google.com/o/oauth2/auth?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectURI)}&response_type=code&scope={Uri.EscapeDataString(scope)}";
var StartUri = new Uri(SpotifyUrl);
var EndUri = new Uri(redirectURI);
// Get Authorization code
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
var decoder = new WwwFormUrlDecoder(new Uri(WebAuthenticationResult.ResponseData).Query);
if (decoder[0].Name != "code")
{
System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {decoder.GetFirstValueByName("error")}.");
return;
}
var autorizationCode = decoder.GetFirstValueByName("code");
//Get Access Token
var pairs = new Dictionary<string, string>();
pairs.Add("code", autorizationCode);
pairs.Add("client_id", clientId);
pairs.Add("redirect_uri", redirectURI);
pairs.Add("grant_type", "authorization_code");
var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
var client = new Windows.Web.Http.HttpClient();
var httpResponseMessage = await client.PostAsync(new Uri("https://www.googleapis.com/oauth2/v4/token"), formContent);
if (!httpResponseMessage.IsSuccessStatusCode)
{
System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {httpResponseMessage.StatusCode}.");
return;
}
string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var jsonObject = Windows.Data.Json.JsonObject.Parse(jsonString);
var accessToken = jsonObject["access_token"].GetString();
//Call Google Calendar API
using (var httpRequest = new Windows.Web.Http.HttpRequestMessage())
{
string calendarAPI = "https://www.googleapis.com/calendar/v3/users/me/calendarList";
httpRequest.Method = Windows.Web.Http.HttpMethod.Get;
httpRequest.RequestUri = new Uri(calendarAPI);
httpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);
var response = await client.SendRequestAsync(httpRequest);
if (response.IsSuccessStatusCode)
{
var listString = await response.Content.ReadAsStringAsync();
//TODO
}
}
}
I have the Google .NET Client working in my UWP app. The trick is that you have to put it in a .NET Standard 2.0 Class Library, expose the API services you need, and then reference that library from your UWP app.
Also, you have to handle the getting the auth token yourself. It's not that much work and the Drive APIs and Calendar APIs work just fine (the only ones I've tried). You can see that I pass in a simple class that contains the auth token and other auth details to a method called Initialize.
Here is the single class I used in the .NET Standard 2.0 class library:
namespace GoogleProxy
{
public class GoogleService
{
public CalendarService calendarService { get; private set; }
public DriveService driveService { get; private set; }
public GoogleService()
{
}
public void Initialize(AuthResult authResult)
{
var credential = GetCredentialForApi(authResult);
var baseInitializer = new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "{your app name here}" };
calendarService = new Google.Apis.Calendar.v3.CalendarService(baseInitializer);
driveService = new Google.Apis.Drive.v3.DriveService(baseInitializer);
}
private UserCredential GetCredentialForApi(AuthResult authResult)
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "{your app client id here}",
ClientSecret = "",
},
Scopes = new string[] { "openid", "email", "profile", "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/calendar.events.readonly", "https://www.googleapis.com/auth/drive.readonly" },
};
var flow = new GoogleAuthorizationCodeFlow(initializer);
var token = new TokenResponse()
{
AccessToken = authResult.AccessToken,
RefreshToken = authResult.RefreshToken,
ExpiresInSeconds = authResult.ExpirationInSeconds,
IdToken = authResult.IdToken,
IssuedUtc = authResult.IssueDateTime,
Scope = "openid email profile https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/drive.readonly",
TokenType = "bearer" };
return new UserCredential(flow, authResult.Id, token);
}
}
}
In order to get the Auth token from google, you have to use custom schemes. Register your app as an 'iOS' app on the google services console and put in a URI scheme (something unique). Then add this scheme to your UWP manifest under Declarations->Protocol. Handle it in your App.xaml.cs:
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)args;
Uri uri = protocolArgs.Uri;
Debug.WriteLine("Authorization Response: " + uri.AbsoluteUri);
locator.AccountsService.GoogleExternalAuthWait.Set(uri.Query);
}
}
That GoogleExternalAuthWait comes from some magical code I found about how to create an asynchronous ManualResetEvent. https://blogs.msdn.microsoft.com/pfxteam/2012/02/11/building-async-coordination-primitives-part-1-asyncmanualresetevent/ It looks like this (I only converted it to generic).
public class AsyncManualResetEvent<T>
{
private volatile TaskCompletionSource<T> m_tcs = new TaskCompletionSource<T>();
public Task<T> WaitAsync() { return m_tcs.Task; }
public void Set(T TResult) { m_tcs.TrySetResult(TResult); }
public bool IsReset => !m_tcs.Task.IsCompleted;
public void Reset()
{
while (true)
{
var tcs = m_tcs;
if (!tcs.Task.IsCompleted ||
Interlocked.CompareExchange(ref m_tcs, new TaskCompletionSource<T>(), tcs) == tcs)
return;
}
}
}
This is how you start the Google Authorization. What happens is it launches an external browser to begin the google signing process and then wait (that's what the AsyncManualResetEvent does). When you're done, Google will launch a URI using your custom scheme. You should get a message dialog saying the browser is trying to open an app... click ok and the AsyncManualResetEvent continues and finishes the auth process. You'll need to make a class that contains all the auth info to pass to your class library.
private async Task<AuthResult> AuthenticateGoogleAsync()
{
try
{
var stateGuid = Guid.NewGuid().ToString();
var expiration = DateTimeOffset.Now;
var url = $"{GoogleAuthorizationEndpoint}?client_id={WebUtility.UrlEncode(GoogleAccountClientId)}&redirect_uri={WebUtility.UrlEncode(GoogleRedirectURI)}&state={stateGuid}&scope={WebUtility.UrlEncode(GoogleScopes)}&display=popup&response_type=code";
var success = Windows.System.Launcher.LaunchUriAsync(new Uri(url));
GoogleExternalAuthWait = new AsyncManualResetEvent<string>();
var query = await GoogleExternalAuthWait.WaitAsync();
var dictionary = query.Substring(1).Split('&').ToDictionary(x => x.Split('=')[0], x => Uri.UnescapeDataString(x.Split('=')[1]));
if (dictionary.ContainsKey("error"))
{
return null;
}
if (!dictionary.ContainsKey("code") || !dictionary.ContainsKey("state"))
{
return null;
}
if (dictionary["state"] != stateGuid)
return null;
string tokenRequestBody = $"code={dictionary["code"]}&redirect_uri={Uri.EscapeDataString(GoogleRedirectURI)}&client_id={GoogleAccountClientId}&access_type=offline&scope=&grant_type=authorization_code";
StringContent content = new StringContent(tokenRequestBody, Encoding.UTF8, "application/x-www-form-urlencoded");
// Performs the authorization code exchange.
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.AllowAutoRedirect = true;
using (HttpClient client = new HttpClient(handler))
{
HttpResponseMessage response = await client.PostAsync(GoogleTokenEndpoint, content);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(stringResponse);
var id = DecodeIdFromJWT((string)json["id_token"]);
var oauthToken = new AuthResult()
{
Provider = AccountType.Google,
AccessToken = (string)json["access_token"],
Expiration = DateTimeOffset.Now + TimeSpan.FromSeconds(int.Parse((string)json["expires_in"])),
Id = id,
IdToken = (string)json["id_token"],
ExpirationInSeconds = long.Parse((string)json["expires_in"]),
IssueDateTime = DateTime.Now,
RefreshToken = (string)json["refresh_token"]
};
return oauthToken;
}
else
{
return null;
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}

I am trying to make an event in google calendar using MS access vba

The plan to make an C# dll file then add that dll file into MS access VBA code by making COM
Everything is working fine in C# code Except the fact that when I use debugger in C# it shows "GoogleWebAuthorizationBrokes.cs not found" and I have to use continue button to execute further code, else the code runs fine and create an event in the google calendar
But when I use call the Method from VBA it goes to the C# but do not execute the entire methode
public string CalendarMethod(string Email, string text)
{
try
{
Msg = "Credential started";
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ClientID",
ClientSecret = "ClientSecret",
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
Msg = "Credential Executed";
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
Msg = "Service Executed";
Event myEvent = new Event()
{
Summary = "Test Event",
Location = "City",
Start = new EventDateTime()
{
DateTime = DateTime.Now,
TimeZone = "America/Los_Angeles"
},
End = new EventDateTime()
{
DateTime = DateTime.Now,
TimeZone = "America/Los_Angeles"
},
Recurrence = new String[] {
"RRULE:FREQ=WEEKLY;BYDAY=MO"
},
Attendees = new List<EventAttendee>()
{
new EventAttendee() { Email = "ishooagarwal#gmail.com" }
}
};
Event recurringEvent = service.Events.Insert(myEvent, "primary").Execute();
Msg = "Event Executed";
return "Executed" + Msg;
}
catch (Exception ex)
{
Console.WriteLine(ex + Msg);
return "Not executed" + Msg +ex;
}
}
It always return from Credential Started
It returns a huge msg at VBA side
System.AggregateException One or more errors occured -------> System.IO.FileNotFoundException could not load filem or assembly "System.Net.Http.Primitives, Version=1.5.0.0, culture=neutral, publicKeyToken=b03......." or one of its dependencies, The system cannot find the file specified
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess{Task task}
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess{Task task}
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.
Looks like when you are calling GoogleWebAuthorizationBroker.AuthorizeAsync method, it is looking for a dependency of System.Net.Http.Primitives which is not on the executing machine.
Make sure this reference is deployed with your application.
This looks like a duplicate issue.
Could not load file or assembly System.Net.Http.Primitives. Located assembly's manifest definition does not match the assembly reference

Using Google APIs Client Library for .NET in portable library

They write:"Supported Platforms: Portable Class Libraries".
But then I write this code in portable class, I have a error:
public async void MyFuncrion()
{
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
//new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read),
new ClientSecrets
{
ClientId = "", //"PUT_CLIENT_ID_HERE",
ClientSecret = "" //"PUT_CLIENT_SECRETS_HERE"
},
new[] { TasksService.Scope.Tasks },
"user",
CancellationToken.None);
var service = new TasksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Tasks API Sample",
});
TaskLists results = await service.Tasklists.List().ExecuteAsync();
foreach (var tasklist in results.Items)
{
TasklistTitlesCollection.Add(tasklist.Title + " " + tasklist.Updated);
// You can get data from the file (using file.Title for example)
// and append it to a TextBox, List, etc.
}
}
Error here: "UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync()", He doen't work in portable library. How can I use library, get tasks without GoogleWebAuthorizationBroker. I already get access token myself and I need only TasksService, maybe I can past my access token and other in the constructor TasksService?
I use this article to breake this wall google .net library
Here i past some my code from PCL and windows8.
PCL:
You need provide DataStore
private async Task<GoogleAuthorizationCodeFlow.Initializer> InitInitializer()
{
_iDataStore = await _userCredential.GetDataStore(); //new StorageDataStore()
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = ClientId, //"PUT_CLIENT_ID_HERE",
ClientSecret = ClientSecret, //"PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { TasksService.Scope.Tasks },
DataStore = (Google.Apis.Util.Store.IDataStore)_iDataStore //new StorageDataStore()
};
return initializer;
}
Then
public async Task<TasksService> Prepare()
{
GoogleAuthorizationCodeFlow.Initializer initializer = await InitInitializer();
Object credential = new Object();
if (String.IsNullOrEmpty(_username))
{
return null;
}
TasksService service = null;
try
{
credential = await _userCredential.GetCredential(initializer, _username);
}
catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException e)
{
service = null;
return service;
}
catch
{
return null;
}
service = new TasksService(new BaseClientService.Initializer
{
HttpClientInitializer = (UserCredential)credential,
ApplicationName = _applicationName,
});
return service;
}
1) In Windows store you need provide StorageDataStore and traverse it to pcl.
2) Use
AuthorizationCodeWinRTInstalledApp(initializer).AuthorizeAsync(username, new CancellationToken(false))
from google library (Google.Apis.Auth.OAuth2) to get your credential and traverse it to pcl
You have two options:
1.Declare foo as async method:
async void Foo()
2.Remove await, and get the result of your task, so your code should look something like:
serCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
//new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read),
new ClientSecrets
{
ClientId = "", //"PUT_CLIENT_ID_HERE",
ClientSecret = "" //"PUT_CLIENT_SECRETS_HERE"
},
new[] { TasksService.Scope.Tasks },
"user",
CancellationToken.None).Result;

Can't list users with Google Directory API Admin SDK

I'm trying to use the AdminService to manage my domain's users and groups, but I'm stuck with a simple request to get all the users of my domain. There is the code in C#:
public Users GetAllUsers()
{
var provider = new AssertionFlowClient(
GoogleAuthenticationServer.Description,
new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))
{
ServiceAccountId = serviceAccountEmail,
Scope = AdminService.Scopes.AdminDirectoryUser.GetStringValue()
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
m_serviceGroup = new AdminService(new BaseClientService.Initializer()
{
Authenticator = auth,
});
var request = m_serviceUser.Users.List();
request.Domain = m_domainName;
return request.Fetch();
}
I'm getting an exception when Fetch() that says:
Code: 403
Message: Not Authorized to access this resource/api
Error: {Message[Not Authorized to access this resource/api] Location[ - ] Reason[forbidden] Domain[global]}
I've followed the instructions here to have enabled API access, and also authorized my service account in domain control panel:
[Security]->[Advanced Setting]->[Authentication]->[Manage third party OAuth Client access]
with scopes:
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user
Admin SDK Service is also enabled in API control panel.
I tried the code to use the DriveService and successfully listed/created/deleted files without any problem, so the authentication part of the code should be alright. I couldn't figure out what else needs to be configured or if there is any other problems with my code.
Thanks for any help.
As described on the page:
Manage API client access
Developers can register their web applications and other API clients with Google to enable access to
data in Google services like Calendar. You can authorize these
registered clients to access your user data without your users having to individually give consent or their passwords. Learn more
The service account needs to act on behave of a user, so when initializing the client the ServiceAccountUser needs to be assigned.
var provider = new AssertionFlowClient(
GoogleAuthenticationServer.Description,
new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))
{
ServiceAccountId = serviceAccountEmail,
Scope = AdminService.Scopes.AdminDirectoryUser.GetStringValue(),
ServiceAccountUser = domainManangerEmail
};
Edit: AssertionFlowClient is deprecated, the following should work:
var cert = new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable);
var serverCredential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new []{DirectoryService.Scope.AdminDirectoryUser},
User = domainManagerAccountEmail
}.FromCertificate(cert));
var dirService = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = serverCredential
});
This code works for me
static void GettingUsers()
{
String serviceAccountEmail = "xxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser},
User = "your USER",
}.FromCertificate(certificate));
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "name of your app",
});
var listReq = service.Users.List();
listReq.Domain = "your domain";
Users allUsers = listReq.Execute();
int counter = 0;
foreach(User myUser in allUsers.UsersValue){
Console.WriteLine("*" + myUser.PrimaryEmail);
counter++;
}
Console.WriteLine(counter);
Console.ReadKey();
For more information, Please take a look in Directory API: Users list.
There are Limits and Quotas.
We will need to give the service ID that we are using the super admin or the right privileges to get pass this error.
Hope this helps.
-Venu Murthy
Work for me.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static string[] Scopes = { DirectoryService.Scope.AdminDirectoryUserReadonly};
static string ApplicationName = "API G Suite implementation guid by amit";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials1/admin-directory_v1-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Directory API service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
////// Define parameters of request.
UsersResource.ListRequest request = service.Users.List();
request.Customer = "my_customer";
request.MaxResults = 10;
request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
////// List users.
IList<User> users = request.Execute().UsersValue;
Console.WriteLine("Users:");
if (users != null && users.Count > 0)
{
foreach (var userItem in users)
{
Console.WriteLine("{0} ({1})", userItem.PrimaryEmail,
userItem.Name.FullName);
}
}
else
{
Console.WriteLine("No users found.");
}
Console.Read();
}
}
}

Categories