forked from salrashid123/google_id_token
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.cs
75 lines (67 loc) · 2.96 KB
/
Main.cs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth;
using Google.Apis.Http;
using Google.Apis.Auth.OAuth2;
using System.Net.Http;
using System.Net.Http.Headers;
using Google.Apis.Logging;
namespace Program
{
public class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
//Google.ApplicationContext.RegisterLogger(new ConsoleLogger(LogLevel.All,true));
var targetAudience = "https://myapp-6w42z6vi3q-uc.a.run.app";
string uri = "https://httpbin.org/get";
string CREDENTIAL_FILE_JSON = "/path/to/svc_accuont.json";
new Program().Run(targetAudience, CREDENTIAL_FILE_JSON, uri).Wait();
}
catch (AggregateException ex)
{
foreach (var err in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + err.Message);
}
}
}
public async Task<string> Run(string targetAudience, string credentialsFilePath, string uri)
{
ServiceAccountCredential saCredential;
using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
{
saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
}
OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(targetAudience).WithTokenFormat(OidcTokenFormat.Standard)).ConfigureAwait(false);
string token = await oidcToken.GetAccessTokenAsync().ConfigureAwait(false);
// the following snippet verifies an id token.
// this step is done on the receiving end of the oidc endpoint
// adding this step in here as just as a demo on how to do this
//var options = SignedTokenVerificationOptions.Default;
SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
{
IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
ExpiryClockTolerance = TimeSpan.FromMinutes(1),
TrustedAudiences = { targetAudience },
CertificatesUrl = "https://www.googleapis.com/oauth2/v3/certs" // default value
};
var payload = await JsonWebSignature.VerifySignedTokenAsync(token, options);
Console.WriteLine("Verified with audience " + payload.Audience);
// end verification
// use the token
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
string response = await httpClient.GetStringAsync(uri).ConfigureAwait(false);
Console.WriteLine(response);
return response;
}
}
}
}