Accessing Google api with multi user - vb.net

Hre's my problem, i open my application in my browser and authenticate to Google. When a user access my application on his computer, he receive this error.
Google.Apis.Requests.RequestError Delegation denied for
pgsolutionssyged2#gmail.com [403] Errors [ Message[Delegation denied
for pgsolutionssyged2#gmail.com] Location[ - ] Reason[forbidden]
Domain[global] ] à
Google.Apis.Requests.ClientServiceRequest`1.Execute() dans
c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:ligne
102 à ManageGoogle.LoadMailGrid(String query, String folderName)
dans C:\Workspaces\SyGED\Dev\WebAppl\Google\ManageGoogle.aspx.vb:ligne
131 à ManageGoogle.trvGMailFolders_NodeClick(Object sender,
RadTreeNodeEventArgs e) dans
C:\Workspaces\SyGED\Dev\WebAppl\Google\ManageGoogle.aspx.vb:ligne 442
à Telerik.Web.UI.RadTreeView.RaisePostBackEvent(String eventArgument)
à System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
In load event of my webpage i call my athenticate method like this :
Protected Sub Authenticate()
Dim datafolder As String = Server.MapPath("App_Data/GoogleService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = Context.User.Identity.Name.ToString
scopes.Add(DriveService.Scope.Drive)
scopes.Add(GmailService.Scope.MailGoogleCom)
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = CLIENT_ID, _
.ClientSecret = CLIENT_SECRET _
}
Dim flow As GoogleAuthorizationCodeFlow
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes _
})
Dim uri As String = Request.Url.ToString()
Dim code = Request("code")
If code IsNot Nothing Then
Dim token = flow.ExchangeCodeForTokenAsync(UserId, code, uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result
' Extract the right state.
Dim oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, UserId, Request("state")).Result
Response.Redirect(oauthState)
Else
Dim result = New AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId, CancellationToken.None).Result
If result.RedirectUri IsNot Nothing Then
' Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri)
Else
' The data store contains the user credential, so the user has been already authenticated.
myDriveService = New DriveService(New BaseClientService.Initializer() With { _
.ApplicationName = "Liens Google SyGED", _
.HttpClientInitializer = result.Credential _
})
myGMailService = New GmailService(New BaseClientService.Initializer() With { _
.ApplicationName = "Liens Google SyGED", _
.HttpClientInitializer = result.Credential _
})
End If
End If
End Sub
What's wrong with my code ?

Related

How do I insert new sheet in Existing google spreadsheet using vb.net?

I am manage to create spreadsheet on google drive using following code.
Now I want to add new sheets in that created spreadsheet.
When I Create new spreadsheet , it contains default sheet having name Sheet1 but I want to rename that sheet or insert more than one sheets in Spreadsheet
Public Function Create(ByVal FileName As String) As String
Try
Dim service = GetGoogleAPPDriveService()
Dim fileMetadata = New Google.Apis.Drive.v3.Data.File()
fileMetadata.Name = FileName
fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"
Dim request As FilesResource.CreateRequest = service.Files.Create(fileMetadata)
request.SupportsTeamDrives = True
request.Fields = "id"
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllcertification)
Dim file = request.Execute
Return file.Id
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPDriveService() As DriveService
Try
Dim Scopes1 As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}
Dim ClientId As String = ""
Dim ClientSecret As String = ""
Dim UserCredentials As UserCredential
Dim stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientId = GoogleClientSecrets.Load(stream).Secrets.ClientId
Dim stream1 = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientSecret = GoogleClientSecrets.Load(stream1).Secrets.ClientSecret
Dim cs = New ClientSecrets()
cs.ClientId = ClientId
cs.ClientSecret = ClientSecret
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes1, Environment.UserName,
CancellationToken.None, New FileDataStore("MyAppsToken", True)).Result
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
Public Function AcceptAllcertification(ByVal sender As Object, ByVal Certification As X509Certificate, ByVal Chain As X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
You need to use the Sheets API for that. Have a look at the AddSheetRequest
Its hard to identify which request has to be used in .net from json file .
I succeed to add sheet in existing Spread sheet . Here I am put vb.net code if any one needed
Public Function Addsheet(ByVal FileId As String, ByVal sheetName As String) As String
Try
Dim serv = GetGoogleAPPSheetService()
Dim updatesheet = New BatchUpdateSpreadsheetRequest
Dim Req_Request As Request = New Request
Dim Req_AddSheet As New AddSheetRequest
Dim prop As New SheetProperties
prop.Title = sheetName
Req_AddSheet.Properties = prop
Req_Request.AddSheet = Req_AddSheet
Dim IList_req As IList(Of Request)
Dim List_req1 = New List(Of Request)
List_req1.Add(Req_Request)
IList_req = List_req1.ToList
updatesheet.Requests = IList_req
Dim req = serv.Spreadsheets.BatchUpdate(updatesheet, FileId)
Dim response = req.Execute
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPSheetService() As SheetsService
Try
Dim UserCredentials As UserCredential
Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "token.json" 'System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function

Google drive API v2 upload fails

I am trying to upload to a Google drive using Google Drive API v2, vb.net 2015,
Windows 10 Pro ver 1909. My code throws an "Error: redirect_uri_mismatch" when the following 'CreateService' procedure is called:
Public Sub CreateService()
Dim ClientId = "xxxxxxxxxxxe9gqt7105uofe6q1hmks4e89m.apps.googleusercontent.com"
Dim ClientSecret = "xxxxxxxxxxxxxxxxxxxxx"
'
Dim MyUserCredential As UserCredential = _
GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() _
With {.ClientId = ClientId, .ClientSecret = ClientSecret}, _
{DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() with _
{.HttpClientInitializer = MyUserCredential, .ApplicationName = "My Drive"})
End Sub

Connecting a VB.NET application with a Google Docs Spreadsheet

I'm creating a small application that can order stuff. The way a user can order something is to input the correct information through a google form, which then would be automatically converted to a Google Spreadsheet.
Now, I want to connect it to my VB application. How can I do that?
You should install sheetsapi v4 to your app.
Here is the code:
Public Class Form3
Shared Scopes As String() = {SheetsService.Scope.SpreadsheetsReadonly}
Shared ApplicationName As String = "Google Sheets API .NET Quickstart"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = ApplicationName })
Dim spreadsheetId As [String] = "your sheet id"
Dim range As [String] = "A2:F"
Dim request As SpreadsheetsResource.ValuesResource.GetRequest = service.Spreadsheets.Values.[Get](spreadsheetId, range)
Dim response As ValueRange = request.Execute()
Dim values As IList(Of IList(Of [Object])) = response.Values
Dim son As String
If values IsNot Nothing AndAlso values.Count > 0 Then
ListBox1.Items.Add("Name, Major")
For Each rol In values
son = rol(0) + " " + rol(1) + " " + rol(2) + " " + rol(4)
' Print columns A and E, which correspond to indices 0 and 4.
ListBox1.Items.Add(son)
Next
End If
End Sub
End Class

How to revoke token for an user

How I can do to revoke token for a user?
This is my authenticate code and I want to reset (revoke) access for one user. This is because I use the GMail API and I want allow my user to change their email if necessary.
Actually the tokens are save with login at moment where token is reach but I must change this value when user decide to change their email.
Dim datafolder As String = Server.MapPath("App_Data/GoogleService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = Context.User.Identity.Name.ToString
scopes.Add(DriveService.Scope.Drive)
scopes.Add(GmailService.Scope.MailGoogleCom)
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = CLIENT_ID, _
.ClientSecret = CLIENT_SECRET _
}
Dim flow As GoogleAuthorizationCodeFlow
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes _
})
Dim uri As String = Request.Url.ToString()
Dim code = Request("code")
If code IsNot Nothing Then
Dim token = flow.ExchangeCodeForTokenAsync(UserId, code, uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result
' Extract the right state.
Dim oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, UserId, Request("state")).Result
Response.Redirect(oauthState)
Else
Dim result = New AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId, CancellationToken.None).Result
If result.RedirectUri IsNot Nothing Then
' Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri)
Else
' The data store contains the user credential, so the user has been already authenticated.
myDriveService = New DriveService(New BaseClientService.Initializer() With { _
.ApplicationName = "Liens Google SyGED", _
.HttpClientInitializer = result.Credential _
})
myGMailService = New GmailService(New BaseClientService.Initializer() With { _
.ApplicationName = "Liens Google SyGED", _
.HttpClientInitializer = result.Credential _
})
End If
End If
You can revoke token by making a call to https://accounts.google.com/o/oauth2/revoke?token={token}
Read https://developers.google.com/identity/protocols/OAuth2WebServer

initialize google api v3 calendarservice with predefined token

I have a server application that needs to read all calendar entries of user calendars. Users have already authorized and i've stored the authcode and refresh token in my server database. Can i initialize a calendar api v3 calendarservice with the oauth2 token that i have saved? i can't figure out how to get it work without asking for user authorization at run time.
i have this working, but i can't determine how to inialize the service with a predefined token.
Dim myscopes As String() = New String() {CalendarService.Scope.Calendar} ' New () {CalendarService.Scope.Calendar}
Dim secrets As New ClientSecrets() With { _
.ClientId = rs.OAuth2Parameters.ClientId, _
.ClientSecret = rs.OAuth2Parameters.ClientSecret _
}
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, myscopes, "sellggltest1#gmail.com", System.Threading.CancellationToken.None).Result
Dim service = New CalendarService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = rs.Application _
})
Dim request As CalendarListResource.ListRequest = service.CalendarList.List()
Dim events As Data.CalendarList = request.Execute()