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);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Authenticates using the client id and credentials, then fetches
        /// the uri.
        /// </summary>
        /// <param name="iapClientId">The client id observed on
        /// https://console.cloud.google.com/apis/credentials. </param>
        /// <param name="credentialsFilePath">Path to the credentials .json file
        /// downloaded from https://console.cloud.google.com/apis/credentials.
        /// </param>
        /// <param name="uri">HTTP uri to fetch.</param>
        /// <returns>The http response body as a string.</returns>
        public async Task <string> InvokeRequestAsync(string iapClientId, string credentialsFilePath, string uri)
        {
            // Read credentials from the credentials .json file.
            ServiceAccountCredential saCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }

            // Request an OIDC token for the Cloud IAP-secured client ID.
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId)).ConfigureAwait(false);

            // Always request the string token from the OIDC token, the OIDC token will refresh the string token if it expires.
            string token = await oidcToken.GetAccessTokenAsync().ConfigureAwait(false);

            // Include the OIDC token in an Authorization: Bearer header to
            // IAP-secured resource
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                string response = await httpClient.GetStringAsync(uri).ConfigureAwait(false);

                return(response);
            }
        }
Ejemplo n.º 3
0
        protected override CredentialsRefreshState GenerateNewCredentials()
        {
            var configuredRegion = AWSConfigs.AWSRegion;
            var region           = string.IsNullOrEmpty(configuredRegion) ? DefaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion);

            Amazon.SecurityToken.Model.Credentials cc = null;
            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;

                var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials());

                OidcToken oidcToken = SourceCredentials.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(TargetAudience).WithTokenFormat(OidcTokenFormat.Standard)).Result;

                TargetAssumeRoleRequest.WebIdentityToken = oidcToken.GetAccessTokenAsync().Result;

                AssumeRoleWithWebIdentityResponse sessionTokenResponse = stsClient.AssumeRoleWithWebIdentityAsync(TargetAssumeRoleRequest).Result;

                cc = sessionTokenResponse.Credentials;
                _logger.InfoFormat("New credentials created for assume role that expire at {0}", cc.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
                return(new CredentialsRefreshState(new ImmutableCredentials(cc.AccessKeyId, cc.SecretAccessKey, cc.SessionToken), cc.Expiration));
            }
            catch (Exception e)
            {
                var msg       = "Error exchanging Google OIDC token for AWS STS ";
                var exception = new InvalidOperationException(msg, e);
                Logger.GetLogger(typeof(GoogleCompatCredentials)).Error(exception, exception.Message);
                throw exception;
            }
        }
        public async Task FetchesAccessToken()
        {
            MockClock clock = new MockClock(new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));

            TokenRefreshManager refreshManager = null;

            refreshManager = new TokenRefreshManager(RefreshTokenAsync, clock, new NullLogger());
            OidcToken token = new OidcToken(refreshManager);

            Assert.Equal("very_fake_access_token", await token.GetAccessTokenAsync(default));
Ejemplo n.º 5
0
        public static async Task <OidcToken> getGoogleOIDCToken(string targetAudience, string credentialsFilePath)
        {
            //GoogleCredential gCredential;
            ServiceAccountCredential saCredential;

            //ComputeCredential cCredential;

            using (var fs = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
            }

            //cCredential = new ComputeCredential();
            //gCredential = await GoogleCredential.GetApplicationDefaultAsync();
            OidcToken oidcToken = await saCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(targetAudience).WithTokenFormat(OidcTokenFormat.Standard)).ConfigureAwait(false);

            return(oidcToken);
        }
Ejemplo n.º 6
0
    /// <summary>
    /// Makes a request to a IAP secured application by first obtaining
    /// an OIDC token.
    /// </summary>
    /// <param name="iapClientId">The client ID observed on
    /// https://console.cloud.google.com/apis/credentials. </param>
    /// <param name="credentialsFilePath">Path to the credentials .json file
    /// downloaded from https://console.cloud.google.com/apis/credentials.
    /// </param>
    /// <param name="uri">HTTP URI to fetch.</param>
    /// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>
    /// <returns>The HTTP response message.</returns>
    public async Task <HttpResponseMessage> InvokeRequestAsync(
        string iapClientId, string credentialsFilePath, string uri, CancellationToken cancellationToken = default)
    {
        // Get the OidcToken.
        // You only need to do this once in your application
        // as long as you can keep a reference to the returned OidcToken.
        OidcToken oidcToken = await GetOidcTokenAsync(iapClientId, credentialsFilePath, cancellationToken).ConfigureAwait(false);

        // Before making an HTTP request, always obtain the string token from the OIDC token,
        // the OIDC token will refresh the string token if it expires.
        string token = await oidcToken.GetAccessTokenAsync(cancellationToken).ConfigureAwait(false);

        // Include the OIDC token in an Authorization: Bearer header to
        // IAP-secured resource
        // Note: Normally you would use an HttpClientFactory to build the httpClient.
        // For simplicity we are building the HttpClient directly.
        using HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return(await httpClient.GetAsync(uri, cancellationToken).ConfigureAwait(false));
    }
Ejemplo 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);

            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);
            }
        }
Ejemplo n.º 8
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);
            }
        }