public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { var signer = SelectSigner(this, _useSigV4, request, clientConfig); var aws4Signer = signer as AWS4Signer; var useV4 = aws4Signer != null; if (useV4) { AmazonS3Uri s3Uri; if (AmazonS3Uri.TryParseAmazonS3Uri(request.Endpoint, out s3Uri)) { if (s3Uri.Bucket != null) { RegionEndpoint cachedRegion; if (BucketRegionDetector.BucketRegionCache.TryGetValue(s3Uri.Bucket, out cachedRegion)) { request.AlternateEndpoint = cachedRegion; } } } var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader; if (request.UseChunkEncoding) request.AWS4SignerResult = signingResult; } else SignRequest(request, metrics, awsAccessKeyId, awsSecretAccessKey); }
internal static async Task<GetHeadResponse> GetHeadAsync(IAmazonS3 s3Client, IClientConfig config, string url, string header) { if (s3Client != null) { using (var httpClient = GetHttpClient(config)) { var request = new HttpRequestMessage(HttpMethod.Head, url); var response = await httpClient.SendAsync(request).ConfigureAwait(false); foreach (var headerPair in response.Headers) { if (string.Equals(headerPair.Key, HeaderKeys.XAmzBucketRegion, StringComparison.OrdinalIgnoreCase)) { foreach (var value in headerPair.Value) { // If there's more than one there's something really wrong. // So just use the first one anyway. return new GetHeadResponse { HeaderValue = value, StatusCode = response.StatusCode }; } } } } } return null; }
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { if (String.IsNullOrEmpty(awsAccessKeyId)) { throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string"); } string dateTime = AWSSDKUtils.GetFormattedTimestampRFC822(0); request.Headers.Add(HeaderKeys.XAmzDateHeader, dateTime); string signature = ComputeHash(dateTime, awsSecretAccessKey, SigningAlgorithm.HmacSHA1); request.Headers.Add(HeaderKeys.AuthorizationHeader, "AWS " + awsAccessKeyId + ":" + signature); }
private static HttpClient GetHttpClient(IClientConfig config) { var proxy = GetProxyIfAvailableAndConfigured(config); if (proxy == null) { return new HttpClient(); } else { return new HttpClient( new HttpClientHandler { Proxy = proxy, UseProxy = true }); } }
/// <summary> /// Signs the specified request with the AWS2 signing protocol by using the /// AWS account credentials given in the method parameters. /// </summary> /// <param name="awsAccessKeyId">The AWS public key</param> /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param> /// <param name="metrics">Request metrics</param> /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param> /// <param name="request">The request to have the signature compute for</param> /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception> public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { if (String.IsNullOrEmpty(awsAccessKeyId)) { throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string"); } request.Parameters["AWSAccessKeyId"] = awsAccessKeyId; request.Parameters["SignatureVersion"] = clientConfig.SignatureVersion; request.Parameters["SignatureMethod"] = clientConfig.SignatureMethod.ToString(); request.Parameters["Timestamp"] = AWSSDKUtils.FormattedCurrentTimestampISO8601; // remove Signature parameter, in case this is a retry request.Parameters.Remove("Signature"); string toSign = AWSSDKUtils.CalculateStringToSignV2(request.Parameters, request.Endpoint.AbsoluteUri); metrics.AddProperty(Metric.StringToSign, toSign); string auth = ComputeHash(toSign, awsSecretAccessKey, clientConfig.SignatureMethod); request.Parameters["Signature"] = auth; }
/// <summary> /// Signs the specified request with the AWS3 signing protocol by using the /// AWS account credentials given in the method parameters. /// </summary> /// <param name="awsAccessKeyId">The AWS public key</param> /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param> /// <param name="metrics">Request metrics</param> /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param> /// <param name="request">The request to have the signature compute for</param> /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception> public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { var signer = SelectSigner(request, clientConfig); var useV4 = signer is AWS4Signer; if (useV4) signer.Sign(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); else { if (UseAws3Https) { SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); } else { SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey); } } }
private static void SignHttps(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { string nonce = Guid.NewGuid().ToString(); string date = AWSSDKUtils.FormattedCurrentTimestampRFC822; string stringToSign; stringToSign = date + nonce; metrics.AddProperty(Metric.StringToSign, stringToSign); string signature = ComputeHash(stringToSign, awsSecretAccessKey, clientConfig.SignatureMethod); StringBuilder builder = new StringBuilder(); builder.Append(HTTPS_SCHEME).Append(" "); builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ","); builder.Append("Algorithm=" + clientConfig.SignatureMethod.ToString() + ","); builder.Append("SignedHeaders=x-amz-date;x-amz-nonce,"); builder.Append("Signature=" + signature); request.Headers[HeaderKeys.XAmzAuthorizationHeader] = builder.ToString(); request.Headers[HeaderKeys.XAmzNonceHeader] = nonce; request.Headers[HeaderKeys.XAmzDateHeader] = date; }
IClient IIpcProvider.GetClient(string connectionString, IClientConfig config) => GetClientFn(connectionString, config);
protected AbstractAWSSigner SelectSigner(AbstractAWSSigner defaultSigner, bool useSigV4Setting, IRequest request, IClientConfig config) { if (UseV4Signing(useSigV4Setting, request, config)) { return(AWS4SignerInstance); } return(defaultSigner); }
public abstract void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey);
/// <summary> /// Constructor for AmazonS3RetryPolicy. /// </summary> /// <param name="config">The IClientConfig object</param> public AmazonS3RetryPolicy(IClientConfig config) : base(config) { }
public UserClientEngine(IUserEvents userEvents, IClientConfig config) { UserEvents = userEvents; Config = config; Init(); }
internal static async Task<GetHeadResponse> GetHeadAsync(IAmazonS3 s3Client, IClientConfig config, string url, string header) { HttpWebRequest httpRequest = GetHeadHttpRequest(config, url); try { using (var httpResponse = await httpRequest.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse) { return HandleWebResponse(header, httpResponse); } } catch (WebException we) { return HandleWebException(header, we); } }
/// <summary> /// Inspects the supplied evidence to return the signer appropriate for the operation /// </summary> /// <param name="useSigV4Setting">Global setting for the service</param> /// <param name="request">The request.</param> /// <param name="config">Configuration for the client</param> /// <returns>True if signature v4 request signing should be used</returns> protected static bool UseV4Signing(bool useSigV4Setting, IRequest request, IClientConfig config) { if (useSigV4Setting || request.UseSigV4 || config.SignatureVersion == "4") return true; // do a cascading series of checks to try and arrive at whether we have // a recognisable region; this is required to use the AWS4 signer RegionEndpoint r = null; if (!string.IsNullOrEmpty(request.AuthenticationRegion)) r = RegionEndpoint.GetBySystemName(request.AuthenticationRegion); if (r == null && !string.IsNullOrEmpty(config.ServiceURL)) { var parsedRegion = AWSSDKUtils.DetermineRegion(config.ServiceURL); if (!string.IsNullOrEmpty(parsedRegion)) r = RegionEndpoint.GetBySystemName(parsedRegion); } if (r == null && config.RegionEndpoint != null) r = config.RegionEndpoint; if (r != null) { var endpoint = r.GetEndpointForService(config.RegionEndpointServiceName, config.UseDualstackEndpoint); if (endpoint != null && (endpoint.SignatureVersionOverride == "4" || string.IsNullOrEmpty(endpoint.SignatureVersionOverride))) return true; } return false; }
/// <summary> /// Calculates the AWS4 signature for a presigned url. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol /// ('host' and 'x-amz-date') will be added to the request before signing. If the Expires parameter /// is present, it is renamed to 'X-Amz-Expires' before signing. /// </param> /// <param name="clientConfig"> /// Adding supporting data for the service call required by the signer (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics"> /// Metrics for the request /// </param> /// <param name="awsAccessKeyId"> /// The AWS public key for the account making the service call. /// </param> /// <param name="awsSecretAccessKey"> /// The AWS secret key for the account making the call, in clear text /// </param> /// <param name="service"> /// The service to sign for /// </param> /// <param name="overrideSigningRegion"> /// The region to sign to, if null then the region the client is configured for will be used. /// </param> /// <exception cref="Amazon.Runtime.SignatureException"> /// If any problems are encountered while signing the request. /// </exception> /// <remarks> /// Parameters passed as part of the resource path should be uri-encoded prior to /// entry to the signer. Parameters passed in the request.Parameters collection should /// be not be encoded; encoding will be done for these parameters as part of the /// construction of the canonical request. /// </remarks> public static AWS4SigningResult SignRequest(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, string service, string overrideSigningRegion) { // clean up any prior signature in the headers if resigning request.Headers.Remove(HeaderKeys.AuthorizationHeader); if (!request.Headers.ContainsKey(HeaderKeys.HostHeader)) { var hostHeader = request.Endpoint.Host; if (!request.Endpoint.IsDefaultPort) hostHeader += ":" + request.Endpoint.Port; request.Headers.Add(HeaderKeys.HostHeader, hostHeader); } var signedAt = AWSSDKUtils.CorrectedUtcNow; var region = overrideSigningRegion ?? DetermineSigningRegion(clientConfig, service, request.AlternateEndpoint, request); // AWS4 presigned urls got S3 are expected to contain a 'UNSIGNED-PAYLOAD' magic string // during signing (other services use the empty-body sha) if (request.Headers.ContainsKey(HeaderKeys.XAmzContentSha256Header)) request.Headers.Remove(HeaderKeys.XAmzContentSha256Header); var sortedHeaders = SortAndPruneHeaders(request.Headers); var canonicalizedHeaderNames = CanonicalizeHeaderNames(sortedHeaders); var parametersToCanonicalize = GetParametersToCanonicalize(request); parametersToCanonicalize.Add(XAmzAlgorithm, AWS4AlgorithmTag); parametersToCanonicalize.Add(XAmzCredential, string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}", awsAccessKeyId, FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat), region, service, Terminator)); parametersToCanonicalize.Add(HeaderKeys.XAmzDateHeader, FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat)); parametersToCanonicalize.Add(HeaderKeys.XAmzSignedHeadersHeader, canonicalizedHeaderNames); var canonicalQueryParams = CanonicalizeQueryParameters(parametersToCanonicalize); var canonicalRequest = CanonicalizeRequest(request.Endpoint, request.ResourcePath, request.HttpMethod, sortedHeaders, canonicalQueryParams, service == "s3" ? UnsignedPayload : EmptyBodySha256); if (metrics != null) metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest); return ComputeSignature(awsAccessKeyId, awsSecretAccessKey, region, signedAt, service, canonicalizedHeaderNames, canonicalRequest, metrics); }
internal static string DetermineService(IClientConfig clientConfig) { return !string.IsNullOrEmpty(clientConfig.AuthenticationServiceName) ? clientConfig.AuthenticationServiceName : AWSSDKUtils.DetermineService(clientConfig.DetermineServiceURL()); }
/// <summary> /// Constructor for AmazonS3RetryPolicy. /// </summary> /// <param name="config">The IClientConfig object</param> public AmazonS3RetryPolicy(IClientConfig config) : base(config) { }
private static void SetProxyIfAvailableAndConfigured(IClientConfig config, HttpWebRequest httpWebRequest) { #if BCL || UNITY || CORECLR var proxy = GetProxyIfAvailableAndConfigured(config); if (proxy != null) { httpWebRequest.Proxy = proxy; } #endif }
public override void Sign(IRequest request, IClientConfig clientConfig, Util.RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { // This is a null signer which a does no-op return; }
public static KeyVault.KeyVaultServiceClient Get(string groupConfigId, IServicesConfig _serviceConfig, IClientConfig _clientConfig, ILogger logger) { var _keyVaultServiceClient = new KeyVault.KeyVaultServiceClient(groupConfigId, _serviceConfig.KeyVaultBaseUrl, true, logger); if (_clientConfig != null && _clientConfig.AppId != null && _clientConfig.AppSecret != null) { _keyVaultServiceClient.SetAuthenticationClientCredential(_clientConfig.AppId, _clientConfig.AppSecret); } else { // uses MSI or dev account _keyVaultServiceClient.SetAuthenticationTokenProvider(); } return(_keyVaultServiceClient); }
public EventsClient(IRestClient client, IClientConfig config) : base(client, config) { }
protected AbstractAWSSigner SelectSigner(AbstractAWSSigner defaultSigner,bool useSigV4Setting, IRequest request, IClientConfig config) { bool usev4Signing = UseV4Signing(useSigV4Setting, request, config); if (usev4Signing) return AWS4SignerInstance; else return defaultSigner; }
public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { this.SignCount++; }
/// <summary> /// Calculates and signs the specified request using the AWS4 signing protocol by using the /// AWS account credentials given in the method parameters. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol /// ('host' and 'x-amz-date') will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Client configuration data encompassing the service call (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics"> /// Metrics for the request. /// </param> /// <param name="awsAccessKeyId"> /// The AWS public key for the account making the service call. /// </param> /// <param name="awsSecretAccessKey"> /// The AWS secret key for the account making the call, in clear text. /// </param> /// <exception cref="Amazon.Runtime.SignatureException"> /// If any problems are encountered while signing the request. /// </exception> /// <remarks> /// Parameters passed as part of the resource path should be uri-encoded prior to /// entry to the signer. Parameters passed in the request.Parameters collection should /// be not be encoded; encoding will be done for these parameters as part of the /// construction of the canonical request. /// </remarks> public AWS4SigningResult SignRequest(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { var signedAt = InitializeHeaders(request.Headers, request.Endpoint); var service = DetermineService(clientConfig); var region = DetermineSigningRegion(clientConfig, service, request.AlternateEndpoint, request); var parametersToCanonicalize = GetParametersToCanonicalize(request); var canonicalParameters = CanonicalizeQueryParameters(parametersToCanonicalize); var bodyHash = SetRequestBodyHash(request); var sortedHeaders = SortAndPruneHeaders(request.Headers); var canonicalRequest = CanonicalizeRequest(request.Endpoint, request.ResourcePath, request.HttpMethod, sortedHeaders, canonicalParameters, bodyHash); if (metrics != null) metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest); return ComputeSignature(awsAccessKeyId, awsSecretAccessKey, region, signedAt, service, CanonicalizeHeaderNames(sortedHeaders), canonicalRequest, metrics); }
private static IWebProxy GetProxyIfAvailableAndConfigured(IClientConfig config) { #if BCL || UNITY || CORECLR return config.GetWebProxy(); #else return null; #endif }
/// <summary> /// Calculates and signs the specified request using the AWS4 signing protocol by using the /// AWS account credentials given in the method parameters. The resulting signature is added /// to the request headers as 'Authorization'. Parameters supplied in the request, either in /// the resource path as a query string or in the Parameters collection must not have been /// uri encoded. If they have, use the SignRequest method to obtain a signature. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol /// ('host' and 'x-amz-date') will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Client configuration data encompassing the service call (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics"> /// Metrics for the request /// </param> /// <param name="awsAccessKeyId"> /// The AWS public key for the account making the service call. /// </param> /// <param name="awsSecretAccessKey"> /// The AWS secret key for the account making the call, in clear text. /// </param> /// <exception cref="Amazon.Runtime.SignatureException"> /// If any problems are encountered while signing the request. /// </exception> public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { var signingResult = SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey); request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader; }
/// <summary> /// This method is called by Inventor when it loads the addin. /// The AddInSiteObject provides access to the Inventor Application object. /// The FirstTime flag indicates if the addin is loaded for the first time. /// </summary> /// <param name="addInSiteObject"></param> /// <param name="firstTime"></param> public void Activate(Inventor.ApplicationAddInSite addInSiteObject, bool firstTime) { try { InventorApplication = addInSiteObject.Application; //retrieve the GUID for this class and assign it to the string member variable //intended to hold it GuidAttribute addInClsid = (GuidAttribute)Attribute.GetCustomAttribute (typeof(StandardAddInServer), typeof(GuidAttribute)); string addInClsidString = "{" + addInClsid.Value + "}"; AddInServerId = addInClsidString; //Set a reference to the user interface manager to determine the interface style UserInterfaceManager userInterfaceManager = InventorApplication.UserInterfaceManager; InterfaceStyleEnum interfaceStyle = userInterfaceManager.InterfaceStyle; RectangleDependencyManager = new RectangleToolsDependencyMapper(); if (interfaceStyle == InterfaceStyleEnum.kRibbonInterface) { if (firstTime == true) { RectangleDependencyManager.InitializeUserInterface(); } } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
internal static HttpWebRequest GetHeadHttpRequest(IClientConfig config, string url) { var httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.Method = "HEAD"; SetProxyIfAvailableAndConfigured(config, httpRequest); return httpRequest; }
private static IWebProxy GetProxyIfAvailableAndConfigured(IClientConfig config) { return(config.GetWebProxy()); }
/// <summary> /// The constructor for HttpRequestMessageFactory. /// </summary> /// <param name="clientConfig">Configuration setting for a client.</param> public HttpRequestMessageFactory(IClientConfig clientConfig) { _clientConfig = clientConfig; }
internal static async Task <GetHeadResponse> GetHeadAsync(IAmazonS3 s3Client, IClientConfig config, string url, string header) { HttpWebRequest httpRequest = GetHeadHttpRequest(config, url); try { using (var httpResponse = await httpRequest.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse) { return(HandleWebResponse(header, httpResponse)); } } catch (WebException we) { return(HandleWebException(header, we)); } }
public void Init(IClientConfig config) { Config = config; Init(); }
/// <summary> /// Marshalls the parameters for a presigned url for a preferred signing protocol. /// </summary> /// <param name="getPreSignedUrlRequest"></param> /// <param name="accessKey"></param> /// <param name="token"></param> /// <param name="aws4Signing"> /// True if AWS4 signing will be used; if the expiry period in the request exceeds the /// maximum allowed for AWS4 (one week), an ArgumentException is thrown. /// </param> /// <returns></returns> private static IRequest Marshall(IClientConfig config, GetPreSignedUrlRequest getPreSignedUrlRequest, string accessKey, string token, bool aws4Signing) { IRequest request = new DefaultRequest(getPreSignedUrlRequest, "AmazonS3"); request.HttpMethod = getPreSignedUrlRequest.Verb.ToString(); var headers = getPreSignedUrlRequest.Headers; foreach (var key in headers.Keys) { request.Headers[key] = headers[key]; } AmazonS3Util.SetMetadataHeaders(request, getPreSignedUrlRequest.Metadata); if (!string.IsNullOrEmpty(token)) { request.Headers[HeaderKeys.XAmzSecurityTokenHeader] = token; } if (getPreSignedUrlRequest.ServerSideEncryptionMethod != null && getPreSignedUrlRequest.ServerSideEncryptionMethod != ServerSideEncryptionMethod.None) { request.Headers.Add(HeaderKeys.XAmzServerSideEncryptionHeader, S3Transforms.ToStringValue(getPreSignedUrlRequest.ServerSideEncryptionMethod)); } if (getPreSignedUrlRequest.IsSetServerSideEncryptionCustomerMethod()) { request.Headers.Add(HeaderKeys.XAmzSSECustomerAlgorithmHeader, getPreSignedUrlRequest.ServerSideEncryptionCustomerMethod); } if (getPreSignedUrlRequest.IsSetServerSideEncryptionKeyManagementServiceKeyId()) { request.Headers.Add(HeaderKeys.XAmzServerSideEncryptionAwsKmsKeyIdHeader, getPreSignedUrlRequest.ServerSideEncryptionKeyManagementServiceKeyId); } if (getPreSignedUrlRequest.IsSetRequestPayer() && getPreSignedUrlRequest.RequestPayer == RequestPayer.Requester) { request.Parameters.Add("x-amz-request-payer", RequestPayer.Requester.Value); } var queryParameters = request.Parameters; var uriResourcePath = new StringBuilder("/"); if (!string.IsNullOrEmpty(getPreSignedUrlRequest.BucketName)) { uriResourcePath.Append(S3Transforms.ToStringValue(getPreSignedUrlRequest.BucketName)); } if (!string.IsNullOrEmpty(getPreSignedUrlRequest.Key)) { if (uriResourcePath.Length > 1) { uriResourcePath.Append("/"); } uriResourcePath.Append(S3Transforms.ToStringValue(getPreSignedUrlRequest.Key)); } var expires = GetSecondsUntilExpiration(config, getPreSignedUrlRequest, aws4Signing); if (aws4Signing && expires > AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry) { var msg = string.Format(CultureInfo.InvariantCulture, "The maximum expiry period for a presigned url using AWS4 signing is {0} seconds", AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry); throw new ArgumentException(msg); } queryParameters.Add(aws4Signing ? "X-Amz-Expires" : "Expires", expires.ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(token)) { queryParameters.Add("x-amz-security-token", token); } if (!aws4Signing) { queryParameters.Add("AWSAccessKeyId", accessKey); } if (getPreSignedUrlRequest.IsSetVersionId()) { request.AddSubResource("versionId", S3Transforms.ToStringValue(getPreSignedUrlRequest.VersionId)); } if (getPreSignedUrlRequest.IsSetUploadId()) { request.AddSubResource("uploadId", S3Transforms.ToStringValue(getPreSignedUrlRequest.UploadId)); } if (getPreSignedUrlRequest.IsSetPartNumber()) { request.AddSubResource("partNumber", S3Transforms.ToStringValue(getPreSignedUrlRequest.PartNumber)); } var responseHeaderOverrides = getPreSignedUrlRequest.ResponseHeaderOverrides; if (!string.IsNullOrEmpty(responseHeaderOverrides.CacheControl)) { queryParameters.Add("response-cache-control", responseHeaderOverrides.CacheControl); } if (!string.IsNullOrEmpty(responseHeaderOverrides.ContentType)) { queryParameters.Add("response-content-type", responseHeaderOverrides.ContentType); } if (!string.IsNullOrEmpty(responseHeaderOverrides.ContentLanguage)) { queryParameters.Add("response-content-language", responseHeaderOverrides.ContentLanguage); } if (!string.IsNullOrEmpty(responseHeaderOverrides.Expires)) { queryParameters.Add("response-expires", responseHeaderOverrides.Expires); } if (!string.IsNullOrEmpty(responseHeaderOverrides.ContentDisposition)) { queryParameters.Add("response-content-disposition", responseHeaderOverrides.ContentDisposition); } if (!string.IsNullOrEmpty(responseHeaderOverrides.ContentEncoding)) { queryParameters.Add("response-content-encoding", responseHeaderOverrides.ContentEncoding); } // Add custom parameters to be included and signed foreach (string k in getPreSignedUrlRequest.Parameters.Keys) { queryParameters.Add(k, getPreSignedUrlRequest.Parameters[k]); } request.MarshallerVersion = 2; request.ResourcePath = uriResourcePath.ToString(); request.UseQueryString = true; return(request); }
private static string DetermineService(IClientConfig clientConfig) { return((!string.IsNullOrEmpty(clientConfig.AuthenticationServiceName)) ? clientConfig.AuthenticationServiceName : AWSSDKUtils.DetermineService(clientConfig.DetermineServiceURL())); }
private static long GetSecondsUntilExpiration(IClientConfig config, GetPreSignedUrlRequest request, bool aws4Signing) { var baselineTime = aws4Signing ? config.CorrectedUtcNow : new DateTime(1970, 1, 1); return(Convert.ToInt64((request.Expires.ToUniversalTime() - baselineTime).TotalSeconds)); }
IClient IIpcProvider.GetClient(string connectionString, IClientConfig config) { return(new Client(config, TcpIpConnectivity.ParsePortNumber(connectionString))); }
public BaseClientImplementation(IRestClient client, IClientConfig config) : base(client, config) { }
protected AbstractAWSSigner SelectSigner(IRequest request, IClientConfig config) { return(SelectSigner(this, useSigV4Setting: false, request, config)); }
/// <summary> /// Create credentials /// </summary> /// <param name="provider"></param> /// <param name="config"></param> public TokenProviderCredentials(ITokenProvider provider, IClientConfig config) : this(config) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); }
/// <summary> /// Constructor for EC2RetryPolicy. /// </summary> /// <param name="config">The IClientConfig object</param> public EC2RetryPolicy(IClientConfig config) : base(config) { ErrorCodesToRetryOn.Add("EC2ThrottledException"); }
/// <summary> /// Create credentials /// </summary> /// <param name="config"></param> protected TokenProviderCredentials(IClientConfig config) { _config = config; _expiry = TimeSpan.FromMinutes(3); // Create new credential after 3 minutes }
/// <summary> /// Convenient factory method. /// </summary> public static Client Create(string moniker, IClientConfig config = null) { var provider = IpcFactory.GetProvider(); return(new Client(provider.GetClient(moniker, config ?? new ClientConfig()))); }
public NotifyingDefaultRetryPolicy(IClientConfig config) : base(config) { MaxBackoffInMilliseconds = 1; }
protected AbstractAWSSigner SelectSigner(IRequest request, IClientConfig config) { return SelectSigner(this, useSigV4Setting: false, request: request, config: config); }
public NotifyingRetryHandler(IClientConfig config) : base(new NotifyingDefaultRetryPolicy(config)) { }
public abstract void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey);
/// <summary> /// Constructor for DynamoDBRRetryPolicy. /// </summary> /// <param name="config">The IClientConfig object</param> public DynamoDBRetryPolicy(IClientConfig config) : base(config) { ErrorCodesToRetryOn.Add("TransactionInProgressException"); }
/// <summary> /// Create console output device code based token provider /// </summary> /// <param name="config"></param> /// <param name="logger"></param> public DeviceCodeTokenProvider(IClientConfig config, ILogger logger) : this(new ConsolePrompt(), config, null, logger) { }
/// <summary> /// Create console output device code based token provider /// </summary> /// <param name="store"></param> /// <param name="config"></param> /// <param name="logger"></param> public DeviceCodeTokenProvider(IClientConfig config, ITokenCacheProvider store, ILogger logger) : this(new ConsolePrompt(), config, store, logger) { }
public static string DetermineSigningRegion(IClientConfig clientConfig, string serviceName, RegionEndpoint alternateEndpoint, IRequest request) { // Alternate endpoint (IRequest.AlternateEndopoint) takes precedence over // client config properties. if (alternateEndpoint != null) { var serviceEndpoint = alternateEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint); if (serviceEndpoint.AuthRegion != null) return serviceEndpoint.AuthRegion; return alternateEndpoint.SystemName; } string authenticationRegion = clientConfig.AuthenticationRegion; if (request != null && request.AuthenticationRegion != null) authenticationRegion = request.AuthenticationRegion; if (!string.IsNullOrEmpty(authenticationRegion)) return authenticationRegion.ToLowerInvariant(); if (!string.IsNullOrEmpty(clientConfig.ServiceURL)) { var parsedRegion = AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL); if (!string.IsNullOrEmpty(parsedRegion)) return parsedRegion.ToLowerInvariant(); } var endpoint = clientConfig.RegionEndpoint; if (endpoint != null) { var serviceEndpoint = endpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint); if (!string.IsNullOrEmpty(serviceEndpoint.AuthRegion)) return serviceEndpoint.AuthRegion; return endpoint.SystemName; } return string.Empty; }
/// <inheritdoc/> public CliAuthenticationProvider(IClientConfig config, ILogger logger) { _vs = new VsAuthenticationProvider(config); _dc = new DeviceCodeTokenProvider(config, logger); }
/// <summary> /// Calculates and signs the specified request using the AWS4 signing protocol by using the /// AWS account credentials given in the method parameters. The resulting signature is added /// to the request headers as 'Authorization'. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol /// ('host' and 'x-amz-date') will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Adding supporting data for the service call required by the signer (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics"> /// Metrics for the request /// </param> /// <param name="awsAccessKeyId"> /// The AWS public key for the account making the service call. /// </param> /// <param name="awsSecretAccessKey"> /// The AWS secret key for the account making the call, in clear text /// </param> /// <exception cref="Amazon.Runtime.SignatureException"> /// If any problems are encountered while signing the request. /// </exception> public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { throw new InvalidOperationException("PreSignedUrl signature computation is not supported by this method; use SignRequest instead."); }
/// <inheritdoc/> public CliAuthenticationProvider(IDeviceCodePrompt prompt, IClientConfig config, ITokenCacheProvider store, ILogger logger) { _vs = new VsAuthenticationProvider(config); _dc = new DeviceCodeTokenProvider(prompt, config, store, logger); }
/// <summary> /// Calculates the AWS4 signature for a presigned url. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol /// ('host' and 'x-amz-date') will be added to the request before signing. If the Expires parameter /// is present, it is renamed to 'X-Amz-Expires' before signing. /// </param> /// <param name="clientConfig"> /// Adding supporting data for the service call required by the signer (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics"> /// Metrics for the request /// </param> /// <param name="awsAccessKeyId"> /// The AWS public key for the account making the service call. /// </param> /// <param name="awsSecretAccessKey"> /// The AWS secret key for the account making the call, in clear text /// </param> /// <exception cref="Amazon.Runtime.SignatureException"> /// If any problems are encountered while signing the request. /// </exception> /// <remarks> /// Parameters passed as part of the resource path should be uri-encoded prior to /// entry to the signer. Parameters passed in the request.Parameters collection should /// be not be encoded; encoding will be done for these parameters as part of the /// construction of the canonical request. /// </remarks> public new AWS4SigningResult SignRequest(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) { return SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey, "s3", null); }
public VenuesClient(IRestClient client, IClientConfig config) : base(client, config) { }
/// <summary> /// Constructor for DynamoDBRRetryPolicy. /// </summary> /// <param name="config">The IClientConfig object</param> public DynamoDBRetryPolicy(IClientConfig config) : base(config) { }
internal static GetHeadResponse GetHead(IAmazonS3 s3Client, IClientConfig config, string url, string header) { #if PCL || CORECLR return GetHeadAsync(s3Client, config, url, header).GetAwaiter().GetResult(); #else HttpWebRequest httpRequest = GetHeadHttpRequest(config, url); try { using (var httpResponse = httpRequest.GetResponse() as HttpWebResponse) { return HandleWebResponse(header, httpResponse); } } catch (WebException we) { return HandleWebException(header, we); } #endif }