Is there a way to reuse Google.Apis.Auth.OAuth2.UserCredential object to authorize SpreadsheetsService? - c#

I'm trying to use the Google Drive and Spreadsheets APIs from a C# console app. I'd like to authorize both services using user credentials with a FileDataStore so that I don't have to reauth my app every single time it runs. Below is how I'm authorizing my Drive service object:
var userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync
(
new ClientSecrets
{
ClientId = "[clientID]",
ClientSecret = "[clientSecret]"
},
new []
{
"https://www.googleapis.com/auth/drive",
"https://spreadsheets.google.com/feeds"
},
"[userName]",
CancellationToken.None,
new FileDataStore("MyApp.GoogleDrive.Auth.Store")
).Result;
var driveService = new DriveService
(
new BaseClientService.Initializer
{
HttpClientInitializer = userCredential,
ApplicationName = "MyApp",
}
);
For the Spreadsheets service, I'm authorizing as prescribed by this guide, but every time I run my app, I have to open a browser to the given auth URL and manually copy in the access token to get it to work.
Is there a way to auth once, obtain the user credentials as above, and use them with both services? Note, I'm authorizing with both the Drive and the Spreadsheets scope, so I don't think there's a problem with that.
I've tried to make it work like this, but I keep getting 400 Bad Request errors when I attempt to insert rows into my spreadsheet:
var auth = new OAuth2Parameters
{
ClientId = "[clientID]",
ClientSecret = "[clientSecret]",
RedirectUri = "[redirectUri]",
Scope = "https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds" ,
AccessToken = userCredential.Token.AccessToken,
RefreshToken = userCredential.Token.RefreshToken,
TokenType = userCredential.Token.TokenType,
};
var requestFactory = new GOAuth2RequestFactory(null, "MyApp", auth);
var spreadsheetsService = new SpreadsheetsService("MyApp")
{
Credentials = new GDataCredentials(userCredential.Token.TokenType + " " + userCredential.Token.AccessToken),
RequestFactory = requestFactory,
};

Is there a way to auth once, obtain the user credentials as above, and use them with both services?
Yes. Provided you have included all scopes and have requested offline access, then you'll get a refresh token which you can store and reuse to get access tokens as needed. Obv you need to consider the security implications.
A 400 bad request doesn't sound like an OAuth issue. I think you have two questions/issues here and it might be worth starting a new thread. Include the http request/response for the 400 in your question.

Related

Create Google Calendar Event With Credentials To Impersonate User with Google Calendar API Library .NET 7 C#

In .NET 7, without specifying a User in the
ServiceAccountCredential.Initializer(original.Id)
block, my calendar event can be created with no errors. But if I specify a user as shown below, I get this error:
Error: unauthorized_client,
Description: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
My service account has domain-wide delegation, allowed scope of
calendar via OAuth2, and I have specifically granted the SA access to the user's calendar (when I try on accounts that have not specifically granted access, I can't create a calendar entry at all).
How do I get appropriate credentials for the service account to impersonate the end user within my domain?
Credit for getting this far to creating-a-serviceaccountcredential-for-a-user-from-a-systems-account
Previous answers don't seem to be working on latest release.
In my API code, which calls the authentication service then creates the event:
Google.Apis.Calendar.v3.CalendarService CS = await SA.AuthenticateServiceAccountSO();
var result = CS.Events.Insert((Event)newEvent, clientemail).Execute();
In Service AuthenticateServiceAccountSO():
public async Task<CalendarService> AuthenticateServiceAccountSO()
{
await Task.Delay(1);
string? serviceAccountCredentialFilePath = _config.GetValue<string>("ServiceAccountFilePath");
string? ClientEmail = _config.GetValue<string>("TestingUserAccountEmail");
string[] scopes = new string[] { CalendarService.Scope.Calendar };
ServiceAccountCredential original = (ServiceAccountCredential)GoogleCredential.FromFile(serviceAccountCredentialFilePath).UnderlyingCredential;
var initializer = new ServiceAccountCredential.Initializer(original.Id)
{
User = ClientEmail,
Key = original.Key,
Scopes = scopes
};
var credential = new ServiceAccountCredential(initializer);
CalendarService service = new(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar_Appointment event Using Service Account Authentication"
});
return service;
}
You're currently copying relatively little of the service account credential - in particular, there's no KeyId. But you can do it all much more simply anyway:
var credential = GoogleCredential.FromFile(serviceAccountCredentialFilePath)
.CreateScoped(CalendarService.Scope.Calendar)
.CreateWithUser(ClientEmail);

Code: BadRequest Message: /me request is only valid with delegated authentication flow

I am trying to upload file on onedrive by using microsoft graph onedrive api.
I am using the method for authentication
Client credentials provider
https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
Like:
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "my-tenantid";
// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
HttpPostedFileBase file = Request.Files;[0];
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
Stream fileContent = file.InputStream;
var res = await graphClient.Me.Drive.Root.ItemWithPath(fileName).Content
.Request()
.PutAsync<DriveItem>(fileContent);
After executing this code then it gives an error in response.
Message: /me request is only valid with delegated authentication flow.
Inner error:
AdditionalData:
date: 2021-12-29T05:30:08
request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
client-request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
ClientRequestId: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
Client credential flow will generate the token on behalf the app itself, so in this scenario, users don't need to sign in first to generate the token stand for the user and then call the api. And because of the design,when you used Me in the graph SDK, your code/app don't know who is Me so it can't work. You should know the user_id first and use /users/{id | userPrincipalName} instead of /Me, in the SDK, that is graphClient.Users["your_user_id"] instead of graphClient.Me
In your scenario, there're 2 solutions, one way is using delegated authentication flow like what you said in your title, another way is get the user id before calling the graph api so that you can use Users["id"] but not Me
===================== Update=========================
I haven't finished the code yet but I found the correct solution now.
Firstly, we can upload file to one drive by this api, you may check the screenshot if this is one drive or sharepoint:
https://graph.microsoft.com/v1.0/users/user_id/drive/items/root:/testupload2.txt:/content
If it is, then the next is easy, using the code below to get an access token and send http request to calling the api:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "your_azuread_clientid";
var clientSecret = "corresponding_client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(scopes);
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
I know it's complex because the api is not the same as this one which has SDK sample, but I think it also deserves to try if they are similar.

How do I use a refresh token to get a new access token for Google SpreadsheetsService

I'm trying to build an application which reads and writes to a private Google Spreadsheet. For this I need to use Google OAuth2.0 .
My problem is that I lose access after 1 hour. I assume this means that the refresh token is not being used correctly. Here is my code for handling authentication:
public static SpreadsheetsService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveAppsReadonly,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
"https://spreadsheets.google.com/feeds",
"https://docs.google.com/feeds"
};
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("MY.APP.Auth.Store")).Result;
SpreadsheetsService service = new SpreadsheetsService(My App");
var requestFactory = new GDataRequestFactory("My App");
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
service.RequestFactory = requestFactory;
return service;
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
return null;
}
}
How do I go about making the refresh token being used correctly?
You are using the current Google .NET client library to authenticate.
When you create a service, it normally will automatically refresh your access token when needed. However, you are sending an access token to an old Gdata library, which doesn't automatically refresh it.
If you create a drive service and run a dummy request against it once an hour it will refresh your access token for you when needed.
var service = new DriveService(new BaseClientService.Initializer() {HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",});
// Dummy request example:
FilesResource.ListRequest list = service.Files.List();
list.MaxResults = 1;
list.Q = "title=dummysearch";
FileList dummyFeed = list.Execute();
// End of Dummy request

My Issue with Google Authentication

I have been using the old version of Google Calendar GData API (v1, v2) since November 2011 in my ASP.NET Applications, allowing Users to retrieve and/or create Calendar Events after submitting their usernames and passwords , and this was working perfectly till 17th of November 2014 just before Google decided to shut down this version of API as announced Calendar GData API / Google Calendar Connectors deprecation
Now I am stuck with the new version of Google APIS Calendar (v3) which forces me to use different scenario of Authentication Process instead of the Traditional one. I don't mind at all using this version of Calendar API as it supports all the needed features but now i don't know how to handle multiple users authentication to use their User Client's ID and Secret which are registered per each user Code Console.
So my question is : Is there any way to let user sign in with his/her normal credentials (Either by Username/Password or Google+ Sign UP feature) and bypassing the process of creating API Project, Enabling the needed APIs and creating new User credentials inside the Console through ASP.net code?
Any Sample code made in C# ASP.net is highly appreciated .
EDIT: Here is my code of Authentication I use
public static CalendarService Authenticate()
{
CalendarService service;
GoogleAuthorizationCodeFlow flow;
string json_File = System.Configuration.ConfigurationManager.AppSettings["Authentication_Path"];
string store_path = System.Configuration.ConfigurationManager.AppSettings["FileStore_Path"];
string url = System.Configuration.ConfigurationManager.AppSettings["Authent_URL"];
using (var stream = new FileStream(json_File, FileMode.Open, FileAccess.Read))
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore(store_path),
ClientSecretsStream = stream,
Scopes = new[] { CalendarService.Scope.Calendar }
});
}
var uri = url;
var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync("TRAININGCALENDAR", CancellationToken.None).Result;
if (result.Credential == null)
{
GoogleCalendar_Bus.Main_Authentication(url, "", "");
}
// The data store contains the user credential, so the user has been already authenticated.
service = new CalendarService(new BaseClientService.Initializer
{
ApplicationName = "Calendar API Sample",
HttpClientInitializer = result.Credential
});
if (result.Credential != null)
{
service = new CalendarService(new BaseClientService.Initializer
{
ApplicationName = "Calendar API Sample",
HttpClientInitializer = result.Credential
});
}
return service;
}
No you need to use Oauth2. When they authenticate you just save the refresh token this will allow you to then get a new access token and you will have access again. You will need to make your own implementation of Idatastore to store these refresh tokens in the database.
The code for creating an implementation of a Idatastore that stores to the Database is to extensive to post here but you can see a basic example here: DatabaseDataStore.cs
Then you can use it like this.
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = _client_id
,ClientSecret = _client_secret }
,scopes
,Environment.UserName
,CancellationToken.None
,new DatabaseDataStore(#"LINDAPC\SQL2012", "LindaTest", "test123", "test", "test")).Result;
Update: Now that I can see your code.
Make sure you have the latested .net client lib. Google.Apis.Calendar.v3 Client Library
your code is using FileDataStore this is what you will need to change. You need to make your own implementation of Idatastore similar to the one I have created DatabaseDatastore.
Your code looks different from how I normally do it.
string[] scopes = new string[] {
CalendarService.Scope.Calendar , // Manage your calendars
CalendarService.Scope.CalendarReadonly // View your Calendars
};
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
This may be due to the fact that you aren't using the most up to date client lib, you can find a sample console application for Google Calendar here unfortunately it also uses FileDatastore you will have to edit it to use DatabaseDataStore. The authentication sample project can be found here Google-Dotnet-Samples/Authentication/ it shows how you can create your own implementation of Idatastore.
I am still working on the tutorial to go along with that sample project I hope to have it completed soon.

Google Tasks API Auth

I have to perform a very simple task to get all the tasks of the account Google through Google Api.
Before i started this questions i read documentation, try search to answers, read tech forums, etc
First of all, I configured Developers Console:
- turned ON required API's: such as Tasks API
- Create and download to my project all generic keys: WEB, SERVICE + P12 KEY, INSTALL APP
- also, Installed in project all requiered Nugets: Auth, Client, Core, Tasks.v1
May be i wrong, but matter of great concern (Common Questions):
1. Why need too many variants of keys?
Google IP is only service and it shall be necessary only one token (key)
For software there is no fundamental difference between back-end, desktop, desktop on IOS/Android/Blackberry, service,...
Software need only get/set data from/to some Google Account.
It's very confuse.
2. Google Developers Console - is not simple and clear tools for ordinal user which want get ability to sync with google apps.
Why Google not have simple trust Token generation for account ?
3. Google documentation is not fully and complex. Too many blank places: such as REST queries - not see any correct and work samples with test data and headers.
May any known - where it is ?
Ok, let's begin practice - simple Desktop app on VS2012:
4. Most of google samples said that i need to use GoogleWebAuthorizationBroker
The Code below is similar as all codes in documenation
client_secret.json - JSON files from Google Developers Console
I were try all JSON files with secret codes and also manually set secrets
But nothing, GoogleWebAuthorizationBroker.AuthorizeAsync try to open bad browser window and ends
UserCredential credential;
var stream = new FileStream(#"..." + client_secret.json, FileMode.Open, FileAccess.Read);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { TasksService.Scope.Tasks },
"user",
CancellationToken.None,
new FileDataStore("Tasks.Auth.Store")).Result;
// Create the service.
var service = new TasksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Api Project"
});
TaskLists results = service.Tasklists.List().Execute();
What is Wrong ???
5. Ок, try to use this:
GoogleAuthorizationCodeFlow flow;
using (var stream = new FileStream(#"..." + client_secret.json, FileMode.Open, FileAccess.Read))
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("Tasks.Auth.Store"),
ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
Scopes = new[] { TasksService.Scope.Tasks }
});
}
var result = new AuthorizationCodeWebApp(flow, "", "")
.AuthorizeAsync("user_id", CancellationToken.None).Result;
// The data store contains the user credential, so the user has been already authenticated.
TasksService service = new TasksService(new BaseClientService.Initializer
{
ApplicationName = "API Project",
HttpClientInitializer = result.Credential
});
var lists = service.Tasklists.List().Execute();
Always - not auth.
I was try changed "user_id" - but nothing
What is wrong ???
5. Ок, try to use this:
string serviceAccountEmail = "xxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"...\\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
//var certificate = new X509Certificate2(#"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { TasksService.Scope.Tasks }
}.FromCertificate(certificate));
// Create the service.
var service = new TasksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "API Project",
});
var lists = service.Tasklists.List().Execute();
if (lists.Items != null)
{
foreach (TaskList lst in lists.Items)
{
var title = lst.Title;
var tasks = service.Tasks.List(lst.Id).Execute();
if (tasks.Items != null)
{
foreach (Task tsk in tasks.Items)
{
}
}
}
}
!!! I have access, but not for my account.
Google return only one EMPTY enemy task list (NOT my 2 lists with many tasks in my account)
What is wrong ???
P.S. Please help. I am in deadlock. I did not expect that Google so bad.
Please, do not redirect me to another forums or topics. I all read before.
Thanks

Categories

Resources