Service Accounts are used for Server to Server communication so the user doesn't need to interact for authentication.
Section 1 Generate Keys for Google Service Account
If you haven’t generated keys yet, follow the steps to generate one or skip to the next section.
Go to https://console.developers.google.com/permissions/serviceaccounts
Select project for which you want the service account.
Create a new service account here. You can add roles and permissions as per your use cases.
Now, besides your account name, click Options >> Create Key.
Select your desired format and hit "Create".
I have generated both the keys for demo.
Section 2 Generate Access Tokens
Now, let's retrieve Acess Token from the above-generated keys. I have taken Console Application here. Install Google.Apis.Auth NuGet package. It will add all the required dependencies.
Add key files to your project and set "Copy to Output Directory" as "Copy Always" or "Copy if newer".
Generate token from JSON key
Write the below code where jsonKeyFilePath is the path to your JSON key file, and scopes takes all the scopes you required in your access token.
-
-
-
-
-
-
- public static async Task<string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)
- {
- using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
- {
- return await GoogleCredential
- .FromStream(stream)
- .CreateScoped(scopes)
- .UnderlyingCredential
- .GetAccessTokenForRequestAsync();
- }
- }
Above is an Asynchronous implementation which can be optionally wrapped as Synchronous like given below.
-
-
-
-
-
-
- public static string GetAccessTokenFromJSONKey(string jsonKeyFilePath, params string[] scopes)
- {
- return GetAccessTokenFromJSONKeyAsync(jsonKeyFilePath, scopes).Result;
- }
Let’s test it for my Google project. I have enabled Google Plus API, so I am requesting the given user’s profile here.
- class TestJSONKey
- {
- public static void GetTokenAndCall()
- {
- var token = GoogleServiceAccount.GetAccessTokenFromJSONKey(
- "Keys/C-SharpCorner-0338f58d564f.json",
- "https://www.googleapis.com/auth/userinfo.profile");
-
- WriteLine(new HttpClient().GetStringAsync($"https://www.googleapis.com/plus/v1/people/110259743757395873050?access_token={token}").Result);
- }
- }
And, call API.
- class Program
- {
- static void Main(string[] args)
- {
-
- TestJSONKey.GetTokenAndCall();
- }
- }
You will get response like this.
Generate token from P12 key
Write the below code where p12KeyFilePath is the path to your JSON key file. You can get serviceAccountEmail from Google Developer Console. The keyPassword will be asked while generating key. By default, it is "notasecret" and scopes takes all the scopes you require in your access token.
-
-
-
-
-
-
-
-
- public static async Task<string> GetAccessTokenFromP12KeyAsync(string p12KeyFilePath, string serviceAccountEmail, string keyPassword = "notasecret", params string[] scopes)
- {
- return await new ServiceAccountCredential(
- new ServiceAccountCredential.Initializer(serviceAccountEmail)
- {
- Scopes = scopes
- }.FromCertificate(
- new X509Certificate2(
- p12KeyFilePath,
- keyPassword,
- X509KeyStorageFlags.Exportable))).GetAccessTokenForRequestAsync();
- }
Above is an Asynchronous implementation which can be optionally wrapped as Synchronous like given below.
-
-
-
-
-
-
-
-
- public static string GetAccessTokenFromP12Key(string p12KeyFilePath, string serviceAccountEmail, string keyPassword, params string[] scopes)
- {
- return GetAccessTokenFromP12KeyAsync(p12KeyFilePath, serviceAccountEmail, keyPassword, scopes).Result;
- }
Let’s test it.
- class TestP12Key
- {
- public static void GetTokenAndCall()
- {
- var token = GoogleServiceAccount.GetAccessTokenFromP12Key(
- "Keys/C-SharpCorner-e0883ada1a3f.p12",
- "[email protected]",
- "notasecret",
- "https://www.googleapis.com/auth/userinfo.profile"
- );
-
- WriteLine(new HttpClient().GetStringAsync($"https://www.googleapis.com/plus/v1/people/110259743757395873050?access_token={token}").Result);
- }
- }
And, call API.
- class Program
- {
- static void Main(string[] args)
- {
-
- TestJSONKey.GetTokenAndCall();
-
-
- TestP12Key.GetTokenAndCall();
- }
- }
You will get a response like this.
You can change the scopes and use access token according to your need. Before making API call, just make sure to enable the same in Google Developer Console for he given project.