Example #1
0
        /// <summary>
        ///
        /// <para>CreateSignedURLForUpload:</para>
        ///
        /// <para>Creates signed url for uploading a file</para>
        ///
        /// <para>Check <seealso cref="IBFileServiceInterface.CreateSignedURLForUpload"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool CreateSignedURLForUpload(
            out string _SignedUrl,
            string _BucketName,
            string _KeyInBucket,
            string _ContentType,
            int _URLValidForMinutes             = 60,
            Action <string> _ErrorMessageAction = null)
        {
            var ContentHeaders = new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new string[] { _ContentType } }
            };

            try
            {
                UrlSigner Signer = UrlSigner.FromServiceAccountCredential(CredentialScoped);
                _SignedUrl = Signer.Sign(_BucketName, _KeyInBucket, TimeSpan.FromMinutes(_URLValidForMinutes), HttpMethod.Put, null, ContentHeaders);
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("BFileServiceGC->CreateSignedURLForUpload: " + e.Message + ", Trace: " + e.StackTrace);
                _SignedUrl = null;
                return(false);
            }
            return(true);
        }
Example #2
0
            public void JsonSourceTest(JsonTest test)
            {
                var timestamp = DateTime.ParseExact(
                    test.Timestamp,
                    "yyyyMMdd'T'HHmmss'Z'",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
                var clock  = new FakeClock(timestamp);
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(clock);

                var actualUrl = signer.Sign(test.Bucket, test.Object,
                                            duration: TimeSpan.FromSeconds(test.Expiration),
                                            requestMethod: s_methods[test.Method],
                                            requestHeaders: test.Headers?.ToDictionary(kvp => kvp.Key, kvp => Enumerable.Repeat(kvp.Value, 1)),
                                            contentHeaders: null);

                // We almost always want the complete URL afterwards, which xUnit doesn't give us.
                if (test.ExpectedUrl != actualUrl)
                {
                    FileLogger.Log($"{test.Description} failure");
                    FileLogger.Log($"Expected: {test.ExpectedUrl}");
                    FileLogger.Log($"Actual: {actualUrl}");
                }
                Assert.Equal(test.ExpectedUrl, actualUrl);
            }
        public async Task <string> GetDownloadUrl(string path, TimeSpan?expiry = null, string contentType = null, string fileName = null, CancellationToken cancellationToken = default)
        {
            path = normalizePath(path);

            cancellationToken.ThrowIfCancellationRequested();

            var urlSigner = UrlSigner.FromServiceAccountCredential(_saCredential);

            cancellationToken.ThrowIfCancellationRequested();

            expiry ??= TimeSpan.MaxValue;

            var signedUrl = await urlSigner.SignAsync(_configuration.Bucket, path, expiry.Value, HttpMethod.Get, cancellationToken : cancellationToken);

            if (contentType is string contentTypeValue)
            {
                signedUrl += "&response-content-type=" + HttpUtility.UrlEncode(contentTypeValue);
            }

            if (fileName is string fileNameValue)
            {
                signedUrl += "&response-content-disposition=" + HttpUtility.UrlEncode(string.Format("attachment; filename=\"{0}\"", fileNameValue));
            }

            cancellationToken.ThrowIfCancellationRequested();

            return(signedUrl);
        }
            public void EncryptionKeyAndHashAreIgnored()
            {
                var signer = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var baseRequestTemplate = RequestTemplate.FromBucket("bucket-name").WithObjectName("object-name");
                var options             = Options
                                          .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                                          .WithSigningVersion(SigningVersion.V2);

                var algorithmTemplate = baseRequestTemplate.WithRequestHeaders(
                    new Dictionary <string, IEnumerable <string> >
                {
                    { EncryptionKey.AlgorithmHeader, new [] { EncryptionKey.AlgorithmValue } }
                });

                var keyAndHashTemplate = baseRequestTemplate.WithRequestHeaders(
                    new Dictionary <string, IEnumerable <string> >
                {
                    { EncryptionKey.AlgorithmHeader, new [] { EncryptionKey.AlgorithmValue } },
                    { EncryptionKey.KeyHeader, new [] { "abc" } },
                    { EncryptionKey.KeyHashHeader, new [] { "def" } }
                });

                var url1 = signer.Sign(algorithmTemplate, options);
                var url2 = signer.Sign(keyAndHashTemplate, options);

                Assert.Equal(url1, url2);

                // However, make sure the encryption algorithm is not ignored.
                var url3 = signer.Sign(baseRequestTemplate, options);

                Assert.NotEqual(url1, url3);
            }
        public async Task SignedURLGet()
        {
            var bucketName = _fixture.BucketName;
            var objectName = _fixture.HelloStorageObjectName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: SignedURLGet
            // Additional: Sign(string,string,TimeSpan,*,*,*)
            // Create a signed URL which can be used to get a specific object for one hour.
            UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential);
            string    url       = urlSigner.Sign(
                bucketName,
                objectName,
                TimeSpan.FromHours(1),
                HttpMethod.Get);

            // Get the content at the created URL.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
Example #6
0
        /// <summary>
        /// DOWNlOAD BUCKET OBJECT BY USING SIGNED URL CREDENTIALS OF ServiceAccountCredential 28/03/2019
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="objectName"></param>
        /// <returns></returns>
        public async static Task <string> GetSignedURL(string bucketName, string objectName)
        {
            try
            {
                var scopes = new string[] { "https://www.googleapis.com/auth/devstorage.read_write" };

                //string cred= Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");

                ServiceAccountCredential cred;

                using (var stream = new FileStream(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"), FileMode.Open, FileAccess.Read))
                {
                    cred = GoogleCredential.FromStream(stream)
                           .CreateScoped(scopes)
                           .UnderlyingCredential as ServiceAccountCredential;
                }

                var urlSigner = UrlSigner.FromServiceAccountCredential(cred);

                return(await urlSigner.SignAsync(bucketName, objectName, TimeSpan.FromMinutes(10), HttpMethod.Get));
            }
            catch (Exception)
            {
                throw new Exception(StaticResource.UnableToGenerateSignedUrl);
            }
        }
Example #7
0
        public async Task SignedURLPut()
        {
            var bucketName = _fixture.BucketName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: SignedURLPut
            // Create a request template that will be used to create the signed URL.
            var destination = "places/world.txt";

            UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate
                                                        .FromBucket(bucketName)
                                                        .WithObjectName(destination)
                                                        .WithHttpMethod(HttpMethod.Put)
                                                        .WithContentHeaders(new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new[] { "text/plain" } }
            });
            // Create options specifying for how long the signer URL will be valid.
            UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1));
            // Create a signed URL which allows the requester to PUT data with the text/plain content-type.
            UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential);
            string    url       = urlSigner.Sign(requestTemplate, options);

            // Upload the content into the bucket using the signed URL.
            string source = "world.txt";

            ByteArrayContent content;

            using (FileStream stream = File.OpenRead(source))
            {
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                content = new ByteArrayContent(data)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("text/plain") }
                };
            }

            HttpResponseMessage response = await httpClient.PutAsync(url, content);

            // End sample

            Assert.True(response.IsSuccessStatusCode);

            var client = StorageClient.Create();
            var result = new MemoryStream();
            await client.DownloadObjectAsync(bucketName, destination, result);

            using (var stream = File.OpenRead(source))
            {
                var data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                Assert.Equal(result.ToArray(), data);
            }

            await client.DeleteObjectAsync(bucketName, destination);
        }
Example #8
0
            public void ExpiryValidation_Invalid(int seconds)
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(new FakeClock());

                Assert.Throws <ArgumentOutOfRangeException>(() => signer.Sign("bucket", "object", TimeSpan.FromSeconds(seconds), HttpMethod.Get));
            }
Example #9
0
            public void ExpiryValidation_Invalid(int seconds)
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(StorageConformanceTestData.TestCredential)
                             .WithClock(new FakeClock());
                var requestTemplate = RequestTemplate.FromBucket("bucket").WithObjectName("object");
                var options         = Options.FromDuration(TimeSpan.FromSeconds(seconds)).WithSigningVersion(SigningVersion.V4);

                Assert.Throws <ArgumentOutOfRangeException>(() => signer.Sign(requestTemplate, options));
            }
Example #10
0
            public void ExpiryValidation_Exactly1Week()
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(new FakeClock());

                // Just testing that no exception is thrown.
                signer.Sign("bucket", "object", TimeSpan.FromDays(7), HttpMethod.Get);
            }
Example #11
0
        public string GetCoverUrl(string userId, int bookId, string coverName)
        {
            var       coverPath   = $"{_baseBookPath}{userId}/{bookId}/{coverName}";
            var       initializer = new ServiceAccountCredential.Initializer(_googleCloudStorageSettings.Id);
            UrlSigner urlSgSigner = UrlSigner.FromServiceAccountCredential(
                new ServiceAccountCredential(initializer.FromPrivateKey(_googleCloudStorageSettings.PrivateKey)));
            string url = urlSgSigner.Sign(_googleCloudStorageSettings.BucketName, coverPath, TimeSpan.FromDays(5));

            return(url);
        }
Example #12
0
        public string GetDownloadUrl(string userId, int bookId, string bookFileName)
        {
            var       bookPath    = $"{_baseBookPath}{userId}/{bookId}/{bookFileName}";
            var       initializer = new ServiceAccountCredential.Initializer(_googleCloudStorageSettings.Id);
            UrlSigner urlSgSigner = UrlSigner.FromServiceAccountCredential(
                new ServiceAccountCredential(initializer.FromPrivateKey(_googleCloudStorageSettings.PrivateKey)));
            string url = urlSgSigner.Sign(_googleCloudStorageSettings.BucketName, bookPath, TimeSpan.FromMinutes(10),
                                          HttpMethod.Get);

            return(url);
        }
Example #13
0
        // ReSharper disable once SuggestBaseTypeForParameter
        public Client(ILogger <Client> logger, IOptions <Setting> options)
        {
            _logger  = logger;
            _options = options.Value;

            GoogleCredential credentials = GetGoogleCredentials();
            var serviceAccountCredential = credentials.UnderlyingCredential as ServiceAccountCredential;

            _urlSigner     = UrlSigner.FromServiceAccountCredential(serviceAccountCredential);
            _storageClient = StorageClient.Create(credentials);
        }
            public async void Unsupported_SignPostPolicy()
            {
                var signer  = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var options = Options
                              .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                              .WithSigningVersion(SigningVersion.V2);
                var postPolicy = PostPolicy.ForBucketAndKey("my-bucket", "my-test-object");

                Assert.Throws <NotSupportedException>(() => signer.Sign(postPolicy, options));
                await Assert.ThrowsAsync <NotSupportedException>(() => signer.SignAsync(postPolicy, options));
            }
Example #15
0
            public void ExpiryValidation_Exactly1Week()
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(StorageConformanceTestData.TestCredential)
                             .WithClock(new FakeClock());

                var requestTemplate = RequestTemplate.FromBucket("bucket").WithObjectName("object");
                var options         = Options.FromDuration(TimeSpan.FromDays(7)).WithSigningVersion(SigningVersion.V4);

                // Just testing that no exception is thrown.
                signer.Sign(requestTemplate, options);
            }
        public async Task <string> GetSignedDownloadUrlAsync(string containerName, string fileName, TimeSpan validityTimeSpan)
        {
            var credential = GoogleCredential.FromJson(_credentialsJson)
                             .CreateScoped(new string[] { "https://www.googleapis.com/auth/devstorage.read_only" })
                             .UnderlyingCredential as ServiceAccountCredential;

            var urlSigner = UrlSigner.FromServiceAccountCredential(credential);

            string signedUrl = await urlSigner.SignAsync(containerName, fileName, validityTimeSpan, HttpMethod.Get).ConfigureAwait(false);

            return(signedUrl);
        }
            public void DefaultHttpMethodIsGet()
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(CreateFakeServiceAccountCredential())
                             .WithSigningVersion(SigningVersion.V2);
                var bucketName = "bucket-name";
                var objectName = "object-name";
                var expiration = DateTimeOffset.UtcNow + TimeSpan.FromDays(1);
                var url1       = signer.Sign(bucketName, objectName, expiration, requestMethod: null);
                var url2       = signer.Sign(bucketName, objectName, expiration, requestMethod: HttpMethod.Get);

                Assert.Equal(url1, url2);
            }
            public async Task ThrowsIfBucketBoundHostSpecified()
            {
                var signer          = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var requestTemplate = RequestTemplate
                                      .FromBucket("bucket-name")
                                      .WithObjectName("object-name");
                var options = Options
                              .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                              .WithSigningVersion(SigningVersion.V2)
                              .WithBucketBoundHostname("my.bucket.domain");

                Assert.Throws <ArgumentOutOfRangeException>(() => signer.Sign(requestTemplate, options));
                await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => signer.SignAsync(requestTemplate, options));
            }
        public async Task <ApiResponse> Handle(GetSignedURLQuery request, CancellationToken cancellationToken)
        {
            ApiResponse response = new ApiResponse();

            try
            {
                string bucketName         = Environment.GetEnvironmentVariable("GOOGLE_BUCKET_NAME");
                string googleCredientials = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");

                if (string.IsNullOrEmpty(googleCredientials))
                {
                    throw new Exception(StaticResource.googleCredentialNotFound);
                }

                var scopes = new string[] { "https://www.googleapis.com/auth/devstorage.read_write" };

                ServiceAccountCredential cred;

                using (var stream = new FileStream(googleCredientials, FileMode.Open, FileAccess.Read))
                {
                    cred = GoogleCredential.FromStream(stream)
                           .CreateScoped(scopes)
                           .UnderlyingCredential as ServiceAccountCredential;
                }

                //var urlSigner = UrlSigner.FromServiceAccountCredential(cred);

                UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(cred);

                response.data.SignedUrl = urlSigner.Sign(
                    bucketName,
                    request.ObjectName,
                    TimeSpan.FromMinutes(10),
                    HttpMethod.Put,
                    contentHeaders: new Dictionary <string, IEnumerable <string> > {
                    { "Content-Type", new[] { "text/plain" } }
                }
                    );

                response.StatusCode = StaticResource.successStatusCode;
                response.Message    = StaticResource.SuccessText;
            }
            catch (Exception exception)
            {
                response.StatusCode = StaticResource.failStatusCode;
                response.Message    = exception.Message;
                await Task.Delay(0);
            }
            return(response);
        }
Example #20
0
        public async Task <FileURLOutputDTO> GetFileUrl(string filename)
        {
            using (Stream stream = new FileStream(this.keypath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var       credential = ServiceAccountCredential.FromServiceAccountData(stream);
                UrlSigner urlSigner  = UrlSigner.FromServiceAccountCredential(credential);
                var       url        = await urlSigner.SignAsync(this.bucketName, filename, TimeSpan.FromHours(1), HttpMethod.Get);

                return(new FileURLOutputDTO()
                {
                    Url = url
                });
            }
        }
Example #21
0
        public string GeneratePreSignedURL(int durationInMinutes, string key)
        {
            string urlString = "";

            var       cred      = _cred.UnderlyingCredential as ServiceAccountCredential;
            UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(cred);

            urlString = urlSigner.Sign(
                _bucketName,
                key,
                TimeSpan.FromMinutes(durationInMinutes),
                HttpMethod.Get);

            return(urlString);
        }
Example #22
0
        public GoogleStorageProvider(GoogleCredential credential, GoogleProviderOptions options)
        {
            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            _client       = StorageClient.Create(credential);
            _serviceEmail = options.Email;
            _bucket       = options.Bucket;

            if (credential.UnderlyingCredential is ServiceAccountCredential cred)
            {
                _urlSigner = UrlSigner.FromServiceAccountCredential(cred);
            }
        }
            public void ResumableEquivalentToPostWithStartHeader()
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(CreateFakeServiceAccountCredential())
                             .WithSigningVersion(SigningVersion.V2);
                var bucketName = "bucket-name";
                var objectName = "object-name";
                var expiration = DateTimeOffset.UtcNow + TimeSpan.FromDays(1);
                var url1       = signer.Sign(bucketName, objectName, expiration, UrlSigner.ResumableHttpMethod);
                var url2       = signer.Sign(bucketName, objectName, expiration, HttpMethod.Post,
                                             new Dictionary <string, IEnumerable <string> > {
                    { "x-goog-resumable", new[] { "start" } }
                });

                Assert.Equal(url1, url2);
            }
        public async Task <string> GetSignedDownloadUrlAsync(string containerName, string fileName, TimeSpan validityTimeSpan, string downloadFileName = null)
        {
            var credential = GoogleCredential.FromJson(_credentialsJson)
                             .CreateScoped(new string[] { "https://www.googleapis.com/auth/devstorage.read_only" })
                             .UnderlyingCredential as ServiceAccountCredential;

            var urlSigner = UrlSigner.FromServiceAccountCredential(credential);

            string signedUrl = await urlSigner.SignAsync(containerName, fileName, validityTimeSpan, HttpMethod.Get).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(downloadFileName))
            {
                signedUrl = $"{signedUrl}&response-content-disposition={HttpUtility.UrlEncode($"attachment; filename=\"{downloadFileName}\"")}";
            }

            return(signedUrl);
        }
Example #25
0
        public async Task PostPolicyAcl()
        {
            var bucketName = _fixture.BucketName;
            var objectName = "places/world.txt";
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;

            // Sample: PostPolicyAcl
            // Create a signed post policy which can be used to upload a specific object and
            // expires in 10 seconds after creation.
            // It also sets a starts-with condition on the acl form element, that should be met
            // by the actual form used for posting.
            UrlSigner urlSigner = UrlSigner
                                  .FromServiceAccountCredential(credential);

            UrlSigner.Options options = UrlSigner.Options
                                        .FromDuration(TimeSpan.FromHours(1))
                                        .WithSigningVersion(SigningVersion.V4)
                                        .WithScheme("https");
            UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName);
            postPolicy.SetStartsWith(UrlSigner.PostPolicyStandardElement.Acl, "public");

            UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options);

            // Create an HTML form including all the fields in the signed post policy.
            StringBuilder form = new StringBuilder();

            form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">");
            foreach (var field in signedPostPolicy.Fields)
            {
                form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">");
            }
            // Include also an acl element with a value that meets the condition set in the policy.
            form.AppendLine("<input type=\"hidden\" name=\"acl\" value=\"public-read\">");
            // Include the file element. It should always be the last element in the form.
            form.AppendLine("<input name=\"file\" type=\"file\">");
            form.AppendLine("<input type=\"submit\" value=\"Upload\">");
            form.AppendLine("</form>");

            // You can now save the form to file and serve it as static content
            // or send it as the response to a request made to your application.
            File.WriteAllText("PostPolicyAcl.html", form.ToString());
            //// End sample

            Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString());
            File.Delete("PostPolicyAcl.html");
        }
            public async Task ThrowsIfQueryParametersSpecified()
            {
                var signer          = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var requestTemplate = RequestTemplate
                                      .FromBucket("bucket-name")
                                      .WithObjectName("object-name")
                                      .WithQueryParameters(
                    new Dictionary <string, IEnumerable <string> >
                {
                    { "param1", new string[] { "value1" } }
                });
                var options = Options
                              .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                              .WithSigningVersion(SigningVersion.V2);

                Assert.Throws <ArgumentException>(() => signer.Sign(requestTemplate, options));
                await Assert.ThrowsAsync <ArgumentException>(() => signer.SignAsync(requestTemplate, options));
            }
        public async Task PostPolicySimple()
        {
            var bucketName = _fixture.BucketName;
            var objectName = "places/world.txt";
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;

            // Sample: PostPolicySimple
            // [START storage_generate_signed_post_policy_v4]
            // Create a signed post policy which can be used to upload a specific object and
            // expires in 1 hour after creation.
            UrlSigner urlSigner = UrlSigner
                                  .FromServiceAccountCredential(credential);

            UrlSigner.Options options = UrlSigner.Options
                                        .FromDuration(TimeSpan.FromHours(1))
                                        .WithSigningVersion(SigningVersion.V4)
                                        .WithScheme("https");
            UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName);
            postPolicy.SetCustomField(UrlSigner.PostPolicyCustomElement.GoogleMetadata, "x-goog-meta-test", "data");

            UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options);

            // Create an HTML form including all the fields in the signed post policy.
            StringBuilder form = new StringBuilder();

            form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">");
            foreach (var field in signedPostPolicy.Fields)
            {
                form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">");
            }
            // Include the file element. It should always be the last element in the form.
            form.AppendLine("<input name=\"file\" type=\"file\">");
            form.AppendLine("<input type=\"submit\" value=\"Upload\">");
            form.AppendLine("</form>");

            // You can now save the form to file and serve it as static content
            // or send it as the response to a request made to your application.
            File.WriteAllText("PostPolicySimple.html", form.ToString());
            // [END storage_generate_signed_post_policy_v4]
            //// End sample

            Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString());
            File.Delete("PostPolicySimple.html");
        }
        public void SigningTest(SigningV4Test test)
        {
            var timestamp = test.Timestamp.ToDateTime();
            var clock     = new FakeClock(timestamp);
            var signer    = UrlSigner
                            .FromServiceAccountCredential(StorageConformanceTestData.TestCredential)
                            .WithClock(clock);

            var requestTemplate = RequestTemplate
                                  .FromBucket(test.Bucket)
                                  .WithObjectName(test.Object)
                                  .WithHttpMethod(s_methods[test.Method])
                                  .WithRequestHeaders(test.Headers.ToDictionary(kvp => kvp.Key, kvp => Enumerable.Repeat(kvp.Value, 1)))
                                  .WithQueryParameters(test.QueryParameters.ToDictionary(kvp => kvp.Key, kvp => Enumerable.Repeat(kvp.Value, 1)));
            var options = Options
                          .FromDuration(TimeSpan.FromSeconds(test.Expiration))
                          .WithSigningVersion(SigningVersion.V4)
                          .WithScheme(test.Scheme);

            switch (test.UrlStyle)
            {
            case UrlStyle.VirtualHostedStyle:
                options = options.WithUrlStyle(UrlSigner.UrlStyle.VirtualHostedStyle);
                break;

            case UrlStyle.BucketBoundHostname:
                options = options.WithBucketBoundHostname(test.BucketBoundHostname);
                break;

            default:
                break;
            }

            var actualUrl = signer.Sign(requestTemplate, options);

            // We almost always want the complete URL afterwards, which xUnit doesn't give us.
            if (test.ExpectedUrl != actualUrl)
            {
                FileLogger.Log($"{test.Description} failure");
                FileLogger.Log($"Expected: {test.ExpectedUrl}");
                FileLogger.Log($"Actual: {actualUrl}");
            }
            Assert.Equal(test.ExpectedUrl, actualUrl);
        }
Example #29
0
            public void SampleRequest_ExplicitParams()
            {
                var clock          = new FakeClock(new DateTime(2018, 11, 19, 5, 56, 54, DateTimeKind.Utc));
                var serviceAccount = CreateFakeServiceAccountCredential("*****@*****.**");
                var signer         = UrlSigner
                                     .FromServiceAccountCredential(serviceAccount)
                                     .WithClock(clock);

                var uriString  = signer.Sign("jessefrank2", "kitten.png", TimeSpan.FromHours(1), signingVersion: SigningVersion.V4);
                var parameters = ExtractQueryParameters(uriString);

                Assert.Equal("GOOG4-RSA-SHA256", parameters["X-Goog-Algorithm"]);
                Assert.Equal("test-account%40spec-test-ruby-samples.iam.gserviceaccount.com%2F20181119%2Fauto%2Fstorage%2Fgoog4_request", parameters["X-Goog-Credential"]);
                Assert.Equal("20181119T055654Z", parameters["X-Goog-Date"]);
                Assert.Equal("3600", parameters["X-Goog-Expires"]);
                Assert.Equal("host", parameters["X-Goog-SignedHeaders"]);

                // No check for the exact signature.
            }
Example #30
0
 /// <summary>
 ///
 /// <para>CreateSignedURLForDownload:</para>
 ///
 /// <para>Creates signed url for downloading a file</para>
 ///
 /// <para>Check <seealso cref="IBFileServiceInterface.CreateSignedURLForDownload"/> for detailed documentation</para>
 ///
 /// </summary>
 public bool CreateSignedURLForDownload(
     out string _SignedUrl,
     string _BucketName,
     string _KeyInBucket,
     int _URLValidForMinutes             = 1,
     Action <string> _ErrorMessageAction = null)
 {
     try
     {
         UrlSigner Signer = UrlSigner.FromServiceAccountCredential(CredentialScoped);
         _SignedUrl = Signer.Sign(_BucketName, _KeyInBucket, TimeSpan.FromMinutes(_URLValidForMinutes), HttpMethod.Get);
     }
     catch (Exception e)
     {
         _ErrorMessageAction?.Invoke("BFileServiceGC->CreateSignedURLForDownload: " + e.Message + ", Trace: " + e.StackTrace);
         _SignedUrl = null;
         return(false);
     }
     return(true);
 }