Google APIs Console. -Login URL : https://accounts.google.com/o/oauth2/auth?response_type=code&client_id= @CLIENTID&client_secret= @CLIENTSECRET&redirect_uri=@REDIRECTURI &scope=@SCOPE&access_type=@ACCESSTYPE&approval_prompt= @APPROVALPROMPT&state=@STATE @CLIENTID = "111111.apps.googleusercontent.com"( will get from Google APIs Console) @CLIENTSECRET = "xXcsad3rg3aqwqg"(will get from Google APIs Console) @REDIRECTURI = "http://localhost:59364/Login.aspx"(will get from Google APIs Console) @SCOPE = "https://www.googleapis.com/auth/drive.file"(Scope) @ACCESSTYPE = "offline" @APPROVALPROMPT= "force" @STATE = "profile" - Above login URL will prompt the user for permission to access their Google Content via app and a code(Authentication_Code) request variable will be retuned in that URL like this: http://YOUR-SITE.com/YOUR-PATH/?state=profile&code=1/fFBGRNJru1FQd44AzqT3Zg
-Use that code to get Refresh Token and Access token(Access token will be valid for 1 hour).
2.Store that Refresh Token in database or in web.config file for future use.
3.Once we get the Refresh token no need to relogin or re-authenticate. Use that Refresh Token to get Access token using below code.
WebRequest request = WebRequest.Create("https://accounts.google.com/o/oauth2/token"); request.Method = "POST"; string postData = "client_id=" + @CLIENTID + "&client_secret=" + @CLIENTSECRET + "&refresh_token=" + @REFRESHTOKEN + "&grant_type=refresh_token"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close();
4.Get Files From Google Drive:
public DataTable RetrieveAllFiles(DriveService service) { List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>(); FilesResource.ListRequest request = service.Files.List(); string fileId = string.Empty; do { try { //Fetch all the files from the google drive. FileList files = request.Fetch(); result.AddRange(files.Items); request.PageToken = files.NextPageToken; fileId = files.Items[0].Id; } catch (Exception e) { objError = new MapsLocator.BusinessLayer.ErrorLog(); objError.LogError(e); request.PageToken = null; } } while (!String.IsNullOrEmpty(request.PageToken)); //Store all the files in a datatable. DataTable dtResult = ConvertToDataTable(result); return dtResult; }