GetPreSignedURL() public method

Create a signed URL allowing access to a resource that would usually require authentication.

When using query string authentication you create a query, specify an expiration time for the query, sign it with your signature, place the data in an HTTP request, and distribute the request to a user or embed the request in a web page.

A PreSigned URL can be generated for GET, PUT, DELETE and HEAD operations on your bucketName, keys, and versions.

public GetPreSignedURL ( GetPreSignedUrlRequest request ) : string
request GetPreSignedUrlRequest The GetPreSignedUrlRequest that defines the /// parameters of the operation.
return string
	static void Main()
	{
		// Connect to Amazon S3 service with authentication
		BasicAWSCredentials basicCredentials =
			new BasicAWSCredentials("AKIAIIYG27E27PLQ6EWQ", 
			"hr9+5JrS95zA5U9C6OmNji+ZOTR+w3vIXbWr3/td");
		AmazonS3Client s3Client = new AmazonS3Client(basicCredentials);

		// Display all S3 buckets
		ListBucketsResponse buckets = s3Client.ListBuckets();
		foreach (var bucket in buckets.Buckets)
		{
			Console.WriteLine(bucket.BucketName);
		}

		// Display and download the files in the first S3 bucket
		string bucketName = buckets.Buckets[0].BucketName;
		Console.WriteLine("Objects in bucket '{0}':", bucketName);
		ListObjectsResponse objects =
			s3Client.ListObjects(new ListObjectsRequest() { BucketName = bucketName });
		foreach (var s3Object in objects.S3Objects)
		{
			Console.WriteLine("\t{0} ({1})", s3Object.Key, s3Object.Size);
			if (s3Object.Size > 0)
			{
				// We have a file (not a directory) --> download it
				GetObjectResponse objData = s3Client.GetObject(
					new GetObjectRequest() { BucketName = bucketName, Key = s3Object.Key });
				string s3FileName = new FileInfo(s3Object.Key).Name;
				SaveStreamToFile(objData.ResponseStream, s3FileName);
			}
		}

		// Create a new directory and upload a file in it
		string path = "uploads/new_folder_" + DateTime.Now.Ticks;
		string newFileName = "example.txt";
		string fullFileName = path + "/" + newFileName;
		string fileContents = "This is an example file created through the Amazon S3 API.";
		s3Client.PutObject(new PutObjectRequest() { 
			BucketName = bucketName, 
			Key = fullFileName,
			ContentBody = fileContents}
		);
		Console.WriteLine("Created a file in Amazon S3: {0}", fullFileName);

		// Share the uploaded file and get a download URL
		string uploadedFileUrl = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
		{ 
			BucketName = bucketName,
			Key = fullFileName,
			Expires = DateTime.Now.AddYears(5)
		});
		Console.WriteLine("File download URL: {0}", uploadedFileUrl);
		System.Diagnostics.Process.Start(uploadedFileUrl);
	}
        public virtual string GeneratePreSignedUrl(AmazonS3Client s3Client, string bucketName, string key)
        {
            // Create the request
            var getPreSignedUrlRequest = new GetPreSignedUrlRequest
            {
                BucketName = bucketName,
                Key = key,
                Expires = DateTime.Now.AddHours(1.0)
            };

            // Submit the request
            return s3Client.GetPreSignedURL(getPreSignedUrlRequest);
        }
Example #3
0
        static void Main(string[] args)
        {
            try
            {
                var client = new AmazonS3Client();

                PutObjectResponse putResponse = client.PutObject(new PutObjectRequest
                {
                    BucketName = BUCKET_NAME,
                    FilePath = TEST_FILE
                });

                GetObjectResponse getResponse = client.GetObject(new GetObjectRequest
                {
                    BucketName = BUCKET_NAME,
                    Key = TEST_FILE
                });

                getResponse.WriteResponseStreamToFile(@"c:\talk\" + TEST_FILE);


                var url = client.GetPreSignedURL(new GetPreSignedUrlRequest
                {
                    BucketName = BUCKET_NAME,
                    Key = TEST_FILE,
                    Expires = DateTime.Now.AddHours(1)
                });

                OpenURL(url);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #4
0
 public static string GeneratePreSignedURL(string bucketName, string objectKey)
 {
     string urlString = "";
     IAmazonS3 s3Client;
     using (s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
     {
         GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
         {
             BucketName = bucketName,
             Key = objectKey,
             Expires = DateTime.Now.AddMinutes(5)
         };
         try
         {
             urlString = s3Client.GetPreSignedURL(request1);
             //string url = s3Client.GetPreSignedURL(request1);
         }
         catch (AmazonS3Exception amazonS3Exception)
         {
             if (amazonS3Exception.ErrorCode != null &&
                 (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                 ||
                 amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
             {
                 Console.WriteLine("Check the provided AWS Credentials.");
                 Console.WriteLine(
                 "To sign up for service, go to http://aws.amazon.com/s3");
             }
             else
             {
                 Console.WriteLine(
                  "Error occurred. Message:'{0}' when listing objects",
                  amazonS3Exception.Message);
             }
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
         }
     }
     return urlString;
 }
Example #5
0
        public void ObtenerRutaAdjunto()
        {
            string regionAws  = "us-west-2";
            string usuarioAws = "CondaiUser";
            string accessKey  = "AKIAIB7EDHV2CPLYDT4A";
            string secretKey  = "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";

            Amazon.Util.ProfileManager.RegisterProfile(usuarioAws, accessKey, secretKey);

            Amazon.RegionEndpoint         region      = Amazon.RegionEndpoint.GetBySystemName(regionAws);
            Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(usuarioAws);

            Amazon.S3.IAmazonS3 s3Client = new Amazon.S3.AmazonS3Client(credentials, region);

            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
            {
                BucketName = "abccondai",
                Key        = "Arena.jpg",
                Expires    = DateTime.Now.AddSeconds(60)
            };

            var a = s3Client.GetPreSignedURL(request);
        }
Example #6
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            if (string.IsNullOrEmpty(s3Settings.AccessKeyID)) Errors.Add("'Access Key' must not be empty.");
            if (string.IsNullOrEmpty(s3Settings.SecretAccessKey)) Errors.Add("'Secret Access Key' must not be empty.");
            if (string.IsNullOrEmpty(s3Settings.Bucket)) Errors.Add("'Bucket' must not be empty.");
            if (GetCurrentRegion(s3Settings) == UnknownEndpoint) Errors.Add("Please select an endpoint.");

            if (IsError)
            {
                return null;
            }

            var region = GetCurrentRegion(s3Settings);

            var s3ClientConfig = new AmazonS3Config();

            if (region.AmazonRegion == null)
            {
                s3ClientConfig.ServiceURL = URLHelpers.ForcePrefix(region.Hostname);
            }
            else
            {
                s3ClientConfig.RegionEndpoint = region.AmazonRegion;
            }

            using (var client = new AmazonS3Client(GetCurrentCredentials(), s3ClientConfig))
            {
                var putRequest = new GetPreSignedUrlRequest
                {
                    BucketName = s3Settings.Bucket,
                    Key = GetObjectKey(fileName),
                    Verb = HttpVerb.PUT,
                    Expires = DateTime.UtcNow.AddMinutes(5),
                    ContentType = Helpers.GetMimeType(fileName)
                };

                var requestHeaders = new NameValueCollection();
                requestHeaders["x-amz-acl"] = "public-read";
                requestHeaders["x-amz-storage-class"] = GetObjectStorageClass();

                putRequest.Headers["x-amz-acl"] = "public-read";
                putRequest.Headers["x-amz-storage-class"] = GetObjectStorageClass();

                var responseHeaders = SendRequestStreamGetHeaders(client.GetPreSignedURL(putRequest), stream, Helpers.GetMimeType(fileName), requestHeaders, method: HttpMethod.PUT);
                if (responseHeaders.Count == 0)
                {
                    Errors.Add("Upload to Amazon S3 failed. Check your access credentials.");
                    return null;
                }

                var eTag = responseHeaders.Get("ETag");
                if (eTag == null)
                {
                    Errors.Add("Upload to Amazon S3 failed.");
                    return null;
                }

                if (GetMd5Hash(stream) == eTag.Replace("\"", ""))
                {
                    return new UploadResult { IsSuccess = true, URL = GetObjectURL(putRequest.Key) };
                }

                Errors.Add("Upload to Amazon S3 failed, uploaded data did not match.");
                return null;
            }
        }
        public virtual string GetUrlForItem(AmazonS3Client s3Client, string key, string bucket)
        {
            var getPreSignedUrlRequest = new GetPreSignedUrlRequest
            {
                BucketName = bucket,
                Key = key,
                Expires = DateTime.Now + TimeSpan.FromMinutes(2)

            };
            return s3Client.GetPreSignedURL(getPreSignedUrlRequest); ;
        }
Example #8
0
        public void PresignedURLSamples()
        {
            {
                #region GetPreSignedURL Sample 1

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    Expires = DateTime.Now.AddMinutes(5)
                };

                // Get path for request
                string path = client.GetPreSignedURL(request);

                // Test by getting contents
                string contents = GetContents(path);

                #endregion
            }

            {
                #region GetPreSignedURL Sample 2

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    Expires = DateTime.Now.AddMinutes(5)
                };
                request.ResponseHeaderOverrides.ContentType = "text/xml+zip";
                request.ResponseHeaderOverrides.ContentDisposition = "attachment; filename=dispName.pdf";
                request.ResponseHeaderOverrides.CacheControl = "No-cache";
                request.ResponseHeaderOverrides.ContentLanguage = "mi, en";
                request.ResponseHeaderOverrides.Expires = "Thu, 01 Dec 1994 16:00:00 GMT";
                request.ResponseHeaderOverrides.ContentEncoding = "x-gzip";

                // Get path for request
                string path = client.GetPreSignedURL(request);

                // Test by getting contents
                string contents = GetContents(path);

                #endregion
            }

            {
                #region GetPreSignedURL Sample 3

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    BucketName = "SampleBucket",
                    Expires = DateTime.Now.AddMinutes(5)
                };

                // Get path for request
                string path = client.GetPreSignedURL(request);

                // Retrieve objects
                string allObjects = GetContents(path);

                #endregion
            }

            {
                #region GetPreSignedURL Sample 4

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    Expires = DateTime.Now.AddMinutes(5)
                };

                // Get path for request
                string path = client.GetPreSignedURL(request);

                // Retrieve buckets
                string allBuckets = GetContents(path);

                #endregion
            }

            {
                #region GetPreSignedURL Sample 5

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    Verb = HttpVerb.PUT,
                    Expires = DateTime.Now.AddDays(10)
                };

                // Get path for request
                string path = client.GetPreSignedURL(request);

                // Prepare data
                byte[] data = UTF8Encoding.UTF8.GetBytes("Sample text.");

                // Configure request
                HttpWebRequest httpRequest = WebRequest.Create(path) as HttpWebRequest;
                httpRequest.Method = "PUT";
                httpRequest.ContentLength = data.Length;

                // Write data to stream
                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();

                // Issue request
                HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;

                #endregion
            }
        }