public async Task OidcTokenProvider_ComputeCredential()
        {
            // This test only executes on GCE so we are certain to have a ComputeCredential.
            GoogleCredential credential = GoogleCredential.FromComputeCredential();

            OidcToken token = await credential.GetOidcTokenAsync(
                OidcTokenOptions.FromTargetAudience("https://this.is.a.test"));

            // Check an access token (really id_token) is available.
            Assert.NotNull(await token.GetAccessTokenAsync());
            // If IdToken is set and AccessToken is not, AccessToken is set to
            // IdToken, so we can always check here that AccessToken is not null.
            Assert.NotNull(token.TokenResponse.AccessToken);
            // The enpoint does not send an expiry, bu we set it to the id_token
            // expiry.
            Assert.NotNull(token.TokenResponse.ExpiresInSeconds);

            var verificationOptions = new SignedTokenVerificationOptions();

            verificationOptions.TrustedAudiences.Add("https://this.is.a.test");

            var payload = await JsonWebSignature.VerifySignedTokenAsync(await token.GetAccessTokenAsync(), verificationOptions);

            Assert.NotNull(payload);
            Assert.Contains("https://this.is.a.test", payload.AudienceAsList);
        }
        private SignedTokenVerificationOptions BuildOptions(
            IClock clock = null, string[] trustedIssuers = null, string[] trustedAudiences = null, TimeSpan?clockTolerance = null)
        {
            var options = new SignedTokenVerificationOptions
            {
                CertificateCache = new FakeCertificateCache(),
                Clock            = clock ?? new MockClock(FakeCertificateCache.ValidJwtGoogleSigned)
            };

            foreach (var issuer in trustedIssuers ?? Enumerable.Empty <string>())
            {
                options.TrustedIssuers.Add(issuer);
            }
            foreach (var audience in trustedAudiences ?? Enumerable.Empty <string>())
            {
                options.TrustedAudiences.Add(audience);
            }
            if (clockTolerance.HasValue)
            {
                options.IssuedAtClockTolerance = clockTolerance.Value;
                options.ExpiryClockTolerance   = clockTolerance.Value;
            }

            return(options);
        }
Esempio n. 3
0
        public void FromAnother_DifferentValueAfterModification()
        {
            var options1 = new SignedTokenVerificationOptions
            {
                CertificatesUrl         = "http://dummy.url",
                ForceCertificateRefresh = true,
                IssuedAtClockTolerance  = TimeSpan.FromSeconds(5),
                ExpiryClockTolerance    = TimeSpan.FromSeconds(10),
                CertificateCache        = new FakeCertificateCache(),
                Clock            = new MockClock(DateTime.UtcNow),
                TrustedAudiences = { "audience" },
                TrustedIssuers   = { "issuers" }
            };

            var options2 = new SignedTokenVerificationOptions(options1);

            options1.CertificatesUrl         = "";
            options1.ForceCertificateRefresh = false;
            options1.IssuedAtClockTolerance  = TimeSpan.Zero;
            options1.ExpiryClockTolerance    = TimeSpan.Zero;
            options1.CertificateCache        = new FakeCertificateCache();
            options1.Clock = new MockClock(DateTime.UtcNow);
            options1.TrustedAudiences.Add("another");
            options1.TrustedIssuers.Add("another");

            Assert.Equal("http://dummy.url", options2.CertificatesUrl);
            Assert.Single(options2.TrustedAudiences, "audience");
            Assert.Single(options2.TrustedIssuers, "issuers");
            Assert.True(options2.ForceCertificateRefresh);
            Assert.Equal(TimeSpan.FromSeconds(5), options2.IssuedAtClockTolerance);
            Assert.Equal(TimeSpan.FromSeconds(10), options2.ExpiryClockTolerance);
            Assert.NotSame(options1.CertificateCache, options2.CertificateCache);
            Assert.NotSame(options1.Clock, options2.Clock);
        }
Esempio n. 4
0
        public void FromAnother_EqualValuesAfterCreation()
        {
            var options1 = new SignedTokenVerificationOptions
            {
                CertificatesUrl         = "http://dummy.url",
                ForceCertificateRefresh = true,
                IssuedAtClockTolerance  = TimeSpan.FromSeconds(5),
                ExpiryClockTolerance    = TimeSpan.FromSeconds(10),
                CertificateCache        = new FakeCertificateCache(),
                Clock            = new MockClock(DateTime.UtcNow),
                TrustedAudiences = { "audience" },
                TrustedIssuers   = { "issuers" }
            };

            var options2 = new SignedTokenVerificationOptions(options1);

            Assert.Equal("http://dummy.url", options2.CertificatesUrl);
            Assert.Single(options2.TrustedAudiences, "audience");
            Assert.Single(options2.TrustedIssuers, "issuers");
            Assert.True(options2.ForceCertificateRefresh);
            Assert.Equal(TimeSpan.FromSeconds(5), options2.IssuedAtClockTolerance);
            Assert.Equal(TimeSpan.FromSeconds(10), options2.ExpiryClockTolerance);
            Assert.IsType <FakeCertificateCache>(options2.CertificateCache);
            Assert.IsType <MockClock>(options2.Clock);
        }
Esempio n. 5
0
        public void Default()
        {
            var options = new SignedTokenVerificationOptions();

            Assert.Null(options.CertificatesUrl);
            Assert.Null(options.CertificateCache);
            Assert.Empty(options.TrustedAudiences);
            Assert.Empty(options.TrustedIssuers);
            Assert.False(options.ForceCertificateRefresh);
            Assert.Equal(TimeSpan.Zero, options.IssuedAtClockTolerance);
            Assert.Equal(TimeSpan.Zero, options.ExpiryClockTolerance);
            Assert.Same(SystemClock.Default, options.Clock);
        }
Esempio n. 6
0
    /// <summary>
    /// Verifies a signed jwt token and returns its payload.
    /// </summary>
    /// <param name="signedJwt">The token to verify.</param>
    /// <param name="expectedAudience">The audience that the token should be meant for.
    /// Validation will fail if that's not the case.</param>
    /// <param name="cancellationToken">The cancellation token to propagate cancellation requests.</param>
    /// <returns>A task that when completed will have as its result the payload of the verified token.</returns>
    /// <exception cref="InvalidJwtException">If verification failed. The message of the exception will contain
    /// information as to why the token failed.</exception>
    public async Task <JsonWebSignature.Payload> VerifyTokenAsync(
        string signedJwt, string expectedAudience, CancellationToken cancellationToken = default)
    {
        SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
        {
            // Use clock tolerance to account for possible clock differences
            // between the issuer and the verifier.
            IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
            ExpiryClockTolerance   = TimeSpan.FromMinutes(1),
            TrustedAudiences       = { expectedAudience }
        };

        return(await JsonWebSignature.VerifySignedTokenAsync(signedJwt, options, cancellationToken : cancellationToken));
    }
Esempio n. 7
0
        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);
            }
        }