In this tutorial, I will show you how to use Google authentication with a JSON file from Google.
First, you need to create a google project in the google dashboard area.
Create a new folder and rename it like Google001Quickstart.
You need to add an A.P.I. to your project, like Google Drive A.P.I., and on the credentials download the JSON file into your project folder named Google001Quickstart and I renamed into client_secret.json.
I start with a new console project in this folder and I add these packages:
1 2 3 4 5 | dotnet new console dotnet add package Microsoft.AspNet.Mvc dotnet add package Google.Apis.Auth dotnet add package Google.Apis.Auth.Mvc dotnet add package Google.Apis.Drive.v3 |
After some testing with the source code, I need to use the Visual Studio 2022 I.D.E. because this will fix some errors and add some new packages to my source code.
The source code I used is simple to understand if you know the basics of the Google authentication process and a little bit of C#.
When I run it this source code will make only the authentication with the browser and show the console message from the source code.
Let’s see this source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System; using System.Security.Cryptography.X509Certificates; using System.Web.Mvc; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Mvc; using Google.Apis.Drive.v3; using Google.Apis.Services; using Google.Apis.Util.Store; namespace Google001Quickstart { internal class Program { public static string[] scopes { get; private set; } [STAThread] static void Main(string[] args) { Console.WriteLine("================================"); try { new Program().Run().Wait(); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { Console.WriteLine("ERROR: " + e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } private async Task Run() { UserCredential credential; scopes = new[] { DriveService.Scope.Drive }; using (var stream = new FileStream("C:\\CSharpProjects\\Google001Quickstart\\client_secret.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.FromStream(stream).Secrets, scopes, "user", CancellationToken.None); } } } } |
The next step is to create a service for this and use the Google A.P.I. but this will be an issue for the next tutorial.