/// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { lock (this._refreshLock) { // If credentials are expired, update if (ShouldUpdate) { if (_currentState != null) { _currentState.Dispose(); } _currentState = GenerateNewCredentials(); // Check if the new credentials are already expired if (ShouldUpdate) { throw new AmazonClientException("The retrieved credentials have already expired"); } } return _currentState.Credentials.Copy(); } }
private CredentialsRefreshState Authenticate(ICredentials userCredential, TimeSpan credentialDuration) { CredentialsRefreshState state; SAMLAssertion assertion; var configuredRegion = AWSConfigs.AWSRegion; var region = string.IsNullOrEmpty(configuredRegion) ? DefaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion); try { assertion = new SAMLAuthenticationController().GetSAMLAssertion(ProfileData.EndpointSettings.Endpoint.ToString(), userCredential, ProfileData.EndpointSettings.AuthenticationType); } catch (Exception e) { throw new AuthenticationFailedException("Authentication failure, unable to obtain SAML assertion.", e); } try { using (var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials(), region)) { var credentials = assertion.GetRoleCredentials(stsClient, ProfileData.RoleArn, credentialDuration); state = new CredentialsRefreshState(credentials, DateTime.UtcNow + credentialDuration); } } catch (Exception e) { var wrappedException = new AmazonClientException("Credential generation failed following successful authentication.", e); var logger = Logger.GetLogger(typeof(StoredProfileSAMLCredentials)); logger.Error(wrappedException, wrappedException.Message); throw wrappedException; } return state; }
/// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { lock (this._refreshLock) { // If credentials are expired, update if (ShouldUpdate) { if (_currentState != null) { _currentState.Dispose(); } _currentState = GenerateNewCredentials(); } return _currentState.Credentials; } }
/// <summary> /// Caches the credentials to player pref's /// </summary> internal void CacheCredentials(CredentialsRefreshState credentialsState) { //TODO: add support for caching }
private void UpdateToGeneratedCredentials(CredentialsRefreshState state) { // Check if the new credentials are already expired if (ShouldUpdate) { throw new AmazonClientException("The retrieved credentials have already expired"); } // Offset the Expiration by PreemptExpiryTime state.Expiration -= PreemptExpiryTime; if (ShouldUpdate) { // This could happen if the default value of PreemptExpiryTime is // overriden and set too high such that ShouldUpdate returns true. _logger.InfoFormat( "The preempt expiry time is set too high: Current time = {0}, Credentials expiry time = {1}, Preempt expiry time = {2}.", DateTime.Now, _currentState.Expiration, PreemptExpiryTime); } }
// Retrieves credentials for the specific role, by making a call to STS private CredentialsRefreshState GetCredentialsForRole(string roleArn) { CredentialsRefreshState credentialsState; // Retrieve Open Id Token // (Reuses existing IdentityId or creates a new one) var identity = this.GetIdentityIdWithCaching(); var getTokenRequest = new GetOpenIdTokenRequest { IdentityId = identity.IdentityId }; // If logins are set, pass them to the GetOpenId call if (Logins.Count > 0) getTokenRequest.Logins = Logins; bool retry = false; GetOpenIdTokenResponse getTokenResult = null; try { getTokenResult = GetOpenId(getTokenRequest); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e, identity)) retry = true; else throw; } if (retry) { return GetCredentialsForRole(roleArn); } string token = getTokenResult.Token; // IdentityId may have changed, save the new value UpdateIdentity(getTokenResult.IdentityId, true); // Assume role with Open Id Token var assumeRequest = new AssumeRoleWithWebIdentityRequest { WebIdentityToken = token, RoleArn = roleArn, RoleSessionName = "NetProviderSession", DurationSeconds = DefaultDurationSeconds }; var credentials = GetStsCredentials(assumeRequest); credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
private CredentialsRefreshState GetRefreshState() { SecurityInfo info = GetServiceInfo(); if (!string.IsNullOrEmpty(info.Message)) { throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Unable to retrieve credentials. Message = \"{0}\".", info.Message)); } SecurityCredentials credentials = GetRoleCredentials(); CredentialsRefreshState refreshState = new CredentialsRefreshState { Credentials = new ImmutableCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.Token), Expiration = credentials.Expiration }; return refreshState; }
/// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { lock (this._refreshLock) { // If credentials are expired, update if (ShouldUpdate) { _currentState = GenerateNewCredentials(); UpdateToGeneratedCredentials(_currentState); } return _currentState.Credentials.Copy(); } }
// Retrieves credentials for the roles defined on the identity pool private CredentialsRefreshState GetPoolCredentials() { CredentialsRefreshState credentialsState; var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = GetIdentityId() }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; var response = GetCredentialsForIdentity(getCredentialsRequest); // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId, true); var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
// Retrieves credentials for the specific role, by making a call to STS private CredentialsRefreshState GetCredentialsForRole(string roleArn) { CredentialsRefreshState credentialsState; // Retrieve Open Id Token // (Reuses existing IdentityId or creates a new one) var getTokenRequest = new GetOpenIdTokenRequest { IdentityId = GetIdentityId() }; // If logins are set, pass them to the GetOpenId call if (Logins.Count > 0) getTokenRequest.Logins = Logins; var getTokenResult = GetOpenId(getTokenRequest); string token = getTokenResult.Token; // IdentityId may have changed, save the new value UpdateIdentity(getTokenResult.IdentityId, true); // Assume role with Open Id Token var assumeRequest = new AssumeRoleWithWebIdentityRequest { WebIdentityToken = token, RoleArn = roleArn, RoleSessionName = "NetProviderSession", DurationSeconds = DefaultDurationSeconds }; var credentials = GetStsCredentials(assumeRequest); credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
// Retrieves credentials for the roles defined on the identity pool private async System.Threading.Tasks.Task<CredentialsRefreshState> GetPoolCredentialsAsync() { CredentialsRefreshState credentialsState; var identity = await GetIdentityIdAsync(RefreshIdentityOptions.Refresh).ConfigureAwait(false); var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = identity }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; if (_identityState != null && !string.IsNullOrEmpty(_identityState.LoginToken)) { getCredentialsRequest.Logins = new Dictionary<string, string>(); getCredentialsRequest.Logins.Add("cognito-identity.amazonaws.com", _identityState.LoginToken); } bool retry = false; GetCredentialsForIdentityResponse response = null; try { response = (await cib.GetCredentialsForIdentityAsync(getCredentialsRequest).ConfigureAwait(false)); // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e)) retry = true; else throw; } if (retry) { return await GetPoolCredentialsAsync(); } var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
// Retrieves credentials for the roles defined on the identity pool private async System.Threading.Tasks.Task<CredentialsRefreshState> GetPoolCredentialsAsync() { CredentialsRefreshState credentialsState; var identityId = await GetIdentityIdAsync().ConfigureAwait(false); var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = identityId }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; var response = (await cib.GetCredentialsForIdentityAsync(getCredentialsRequest).ConfigureAwait(false)); // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId, true); var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
/// <summary> /// Clears currently-stored credentials, forcing the next GetCredentials call to generate new credentials. /// </summary> public virtual void ClearCredentials() { _currentState = null; }
private CredentialsRefreshState GetEarlyRefreshState(CredentialsRefreshState state) { // New expiry time = Now + _refreshAttemptPeriod + PreemptExpiryTime var newExpiryTime = DateTime.Now + _refreshAttemptPeriod + PreemptExpiryTime; // Use this only if the time is earlier than the default expiration time if (newExpiryTime.ToUniversalTime() > state.Expiration.ToUniversalTime()) newExpiryTime = state.Expiration; return new CredentialsRefreshState { Credentials = state.Credentials.Copy(), Expiration = newExpiryTime }; }
private CredentialsRefreshState Authenticate(ICredentials userCredential) { CredentialsRefreshState state; var region = Options.STSRegion; if (region == null) { region = FallbackRegionFactory.GetRegionEndpoint(); } if (region == null) { region = DefaultSTSClientRegion; } ICoreAmazonSTS coreSTSClient = null; try { var stsConfig = ServiceClientHelpers.CreateServiceConfig( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME); stsConfig.RegionEndpoint = region; if (Options.ProxySettings != null) { stsConfig.SetWebProxy(Options.ProxySettings); } coreSTSClient = ServiceClientHelpers.CreateServiceFromAssembly <ICoreAmazonSTS>( ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CLASS_NAME, new AnonymousAWSCredentials(), stsConfig); } catch (Exception e) { var msg = string.Format(CultureInfo.CurrentCulture, "Assembly {0} could not be found or loaded. This assembly must be available at runtime to use this profile class.", ServiceClientHelpers.STS_ASSEMBLY_NAME); throw new InvalidOperationException(msg, e); } var samlCoreSTSClient = coreSTSClient; try { var credentials = samlCoreSTSClient.CredentialsFromSAMLAuthentication( SAMLEndpoint.EndpointUri.ToString(), SAMLEndpoint.AuthenticationType.ToString(), RoleArn, MaximumCredentialTimespan, userCredential); RegisterRoleSession(credentials); state = new CredentialsRefreshState(credentials, credentials.Expires); } catch (Exception e) { var wrappedException = new AmazonClientException("Credential generation from SAML authentication failed.", e); var logger = Logger.GetLogger(typeof(FederatedAWSCredentials)); logger.Error(wrappedException, wrappedException.Message); throw wrappedException; } return(state); }
/// <summary> /// Returns an instance of ImmutableCredentials for this instance /// </summary> /// <returns></returns> public override ImmutableCredentials GetCredentials() { lock (this._refreshLock) { // If credentials are expired, update if (ShouldUpdate) { if (_currentState != null) { _currentState.Dispose(); } _currentState = GenerateNewCredentials(); // Check if the new credentials are already expired if (ShouldUpdate) { throw new AmazonClientException("The retrieved credentials have already expired"); } // Offset the Expiration by PreemptExpiryTime _currentState.Expiration -= PreemptExpiryTime; if (ShouldUpdate) { // This should happen if the default value of PreemptExpiryTime is // overriden and set too high such that ShouldUpdate returns true. _logger.InfoFormat("The preempt expiry time is set too high: {0}.", PreemptExpiryTime); } } return _currentState.Credentials.Copy(); } }
// Retrieves credentials for the roles defined on the identity pool private async System.Threading.Tasks.Task<CredentialsRefreshState> GetPoolCredentialsAsync() { CredentialsRefreshState credentialsState; var identity = await GetIdentityIdWithCachingAsync().ConfigureAwait(false); var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = identity.IdentityId }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; bool retry = false; GetCredentialsForIdentityResponse response = null; try { response = (await cib.GetCredentialsForIdentityAsync(getCredentialsRequest).ConfigureAwait(false)); // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId, true); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e, identity)) retry = true; else throw; } if (retry) { return await GetPoolCredentialsAsync(); } var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
// Retrieves credentials for the roles defined on the identity pool private CredentialsRefreshState GetPoolCredentials() { CredentialsRefreshState credentialsState; var identity = this.GetIdentityIdWithCaching(); var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = identity.IdentityId }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; bool retry = false; GetCredentialsForIdentityResponse response = null; try { response = GetCredentialsForIdentity(getCredentialsRequest); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e, identity)) retry = true; else throw; } if (retry) { return GetPoolCredentials(); } // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId, true); var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
/// <summary> /// Clears currently-stored credentials, forcing the next GetCredentials call to generate new credentials. /// </summary> protected void ClearCredentials() { _currentState = null; }
// Retrieves credentials for the roles defined on the identity pool private CredentialsRefreshState GetPoolCredentials() { CredentialsRefreshState credentialsState; var identity = this.GetIdentityId(RefreshIdentityOptions.Refresh); var getCredentialsRequest = new GetCredentialsForIdentityRequest { IdentityId = identity }; if (Logins.Count > 0) getCredentialsRequest.Logins = Logins; //incase its BYOI provider override the logins dictionary with the new instance and set the values for cognito-identity provider if (_identityState != null && !string.IsNullOrEmpty(_identityState.LoginToken)) { getCredentialsRequest.Logins = new Dictionary<string, string>(); getCredentialsRequest.Logins["cognito-identity.amazonaws.com"] = _identityState.LoginToken; } bool retry = false; GetCredentialsForIdentityResponse response = null; try { response = GetCredentialsForIdentity(getCredentialsRequest); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e)) retry = true; else throw; } if (retry) { return GetPoolCredentials(); } // IdentityId may have changed, save the new value UpdateIdentity(response.IdentityId); var credentials = response.Credentials; credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
public async override System.Threading.Tasks.Task<ImmutableCredentials> GetCredentialsAsync() { // If credentials are expired, update if (ShouldUpdate) { var state = await GenerateNewCredentialsAsync().ConfigureAwait(false); lock (this._refreshLock) { _currentState = state; UpdateToGeneratedCredentials(_currentState); } } return _currentState.Credentials.Copy(); }
protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_currentState != null) { _currentState.Dispose(); _currentState = null; } if (_logger!=null) { _logger.Flush(); } } _disposed = true; } }
private void UpdateToGeneratedCredentials(CredentialsRefreshState state) { // Check if the new credentials are already expired if (ShouldUpdate) { var errorMessage = string.Format(CultureInfo.InvariantCulture, "The retrieved credentials have already expired: Now = {0}, Credentials expiration = {1}", DateTime.Now, state.Expiration); throw new AmazonClientException(errorMessage); } // Offset the Expiration by PreemptExpiryTime state.Expiration -= PreemptExpiryTime; if (ShouldUpdate) { // This could happen if the default value of PreemptExpiryTime is // overriden and set too high such that ShouldUpdate returns true. var logger = Logger.GetLogger(typeof(RefreshingAWSCredentials)); logger.InfoFormat( "The preempt expiry time is set too high: Current time = {0}, Credentials expiry time = {1}, Preempt expiry time = {2}.", DateTime.Now, _currentState.Expiration, PreemptExpiryTime); } }
protected override CredentialsRefreshState GenerateNewCredentials() { var sessionCredentials = _stsClient.GetSessionToken(new GetSessionTokenRequest()).GetSessionTokenResult.Credentials; var state = new CredentialsRefreshState { Credentials = new ImmutableCredentials(sessionCredentials.AccessKeyId, sessionCredentials.SecretAccessKey, sessionCredentials.SessionToken, false), Expiration = sessionCredentials.Expiration }; return state; }
protected override CredentialsRefreshState GenerateNewCredentials() { CredentialsRefreshState newState = null; try { // Attempt to get early credentials. OK to fail at this point. newState = GetRefreshState(); } catch (Exception e) { var logger = Logger.GetLogger(typeof(InstanceProfileAWSCredentials)); logger.InfoFormat("Error getting credentials from Instance Profile service: {0}", e); } // If successful, save new credentials if (newState != null) _currentRefreshState = newState; // If still not successful (no credentials available at start), attempt once more to // get credentials, but now without swallowing exception if (_currentRefreshState == null) _currentRefreshState = GetRefreshState(); // Return credentials that will expire in at most one hour CredentialsRefreshState state = GetEarlyRefreshState(_currentRefreshState); return state; }
private async System.Threading.Tasks.Task<CredentialsRefreshState> GetCredentialsForRoleAsync(string roleArn) { CredentialsRefreshState credentialsState; // Retrieve Open Id Token // (Reuses existing IdentityId or creates a new one) var identityId = await GetIdentityIdAsync().ConfigureAwait(false); var getTokenRequest = new GetOpenIdTokenRequest { IdentityId = identityId }; // If logins are set, pass them to the GetOpenId call if (Logins.Count > 0) getTokenRequest.Logins = Logins; var getTokenResult = await cib.GetOpenIdTokenAsync(getTokenRequest).ConfigureAwait(false); string token = getTokenResult.Token; // IdentityId may have changed, save the new value UpdateIdentity(getTokenResult.IdentityId, true); // Assume role with Open Id Token var assumeRequest = new AssumeRoleWithWebIdentityRequest { WebIdentityToken = token, RoleArn = roleArn, RoleSessionName = "NetProviderSession", DurationSeconds = DefaultDurationSeconds }; var credentials = (await sts.AssumeRoleWithWebIdentityAsync(assumeRequest).ConfigureAwait(false)).Credentials; // Return new refresh state (credentials and expiration) credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }
/// <summary> /// Refresh credentials after expiry. If the role profile is configured with user identity /// information and a callback has been registered to obtain the user credential, the callback /// will be invoked ahead of authentication. For role profiles configured with user identity /// but no callback registration, the SDK will fall back to attempting to use the default /// user identity of the current process. /// </summary> /// <returns></returns> protected override CredentialsRefreshState GenerateNewCredentials() { Validate(); // If the profile indicates the user has already authenticated and received // credentials which are still valid, adopt them instead of requiring a fresh // authentication. SAMLImmutableCredentials currentSession; if (TryGetRoleSession(out currentSession)) { // Since cached role session credentials can be obtained, stored credentials exist // and they were not expired. However, since the stored credentials are actual // expiration time and not preempt expiration time we must preempt the expiration // to check that they will not expire before this call completes. var cachedState = new CredentialsRefreshState(currentSession, currentSession.Expires); // Use the cached credentials as long as they are not within the preempt expiry window // or have since actually expired since the prior call to TryGetRoleSession. //Verify the actual expiration is not within the preempt expiration time. if (!cachedState.IsExpiredWithin(PreemptExpiryTime)) { // The credentials have plenty of time left before they expire so they can be used. After // return the expiration time will be preempted for future checks using ShouldUpdate. return(cachedState); } } CredentialsRefreshState newState = null; var attempts = 0; do { try { NetworkCredential userCredential = null; if (Options.UserIdentity != null) { if (Options.CredentialRequestCallback != null) { var callbackArgs = new CredentialRequestCallbackArgs { ProfileName = Options.ProfileName, UserIdentity = Options.UserIdentity, CustomState = Options.CustomCallbackState, PreviousAuthenticationFailed = attempts > 0 }; userCredential = Options.CredentialRequestCallback(callbackArgs); if (userCredential == null) // user declined to authenticate { throw new FederatedAuthenticationCancelledException( "User cancelled credential request."); } } else { var logger = Logger.GetLogger(typeof(FederatedAWSCredentials)); logger.InfoFormat( "FederatedAWSCredentials configured for a specific user but no credential request callback registered; falling back to default identity."); } } newState = Authenticate(userCredential); } catch (FederatedAuthenticationFailureException) { if (attempts < MaxAuthenticationRetries) { attempts++; } else { throw; } } } while (newState == null && attempts < MaxAuthenticationRetries); return(newState); }
private async System.Threading.Tasks.Task<CredentialsRefreshState> GetCredentialsForRoleAsync(string roleArn) { CredentialsRefreshState credentialsState; // Retrieve Open Id Token // (Reuses existing IdentityId or creates a new one) var identity = await GetIdentityIdAsync(RefreshIdentityOptions.Refresh).ConfigureAwait(false); var getTokenRequest = new GetOpenIdTokenRequest { IdentityId = identity }; // If logins are set, pass them to the GetOpenId call if (Logins.Count > 0) getTokenRequest.Logins = Logins; bool retry = false; GetOpenIdTokenResponse getTokenResult = null; try { getTokenResult = await cib.GetOpenIdTokenAsync(getTokenRequest).ConfigureAwait(false); } catch (AmazonCognitoIdentityException e) { if (ShouldRetry(e)) retry = true; else throw; } if (retry) { return await GetCredentialsForRoleAsync(roleArn); } string token = getTokenResult.Token; // IdentityId may have changed, save the new value UpdateIdentity(getTokenResult.IdentityId); // Assume role with Open Id Token var assumeRequest = new AssumeRoleWithWebIdentityRequest { WebIdentityToken = token, RoleArn = roleArn, RoleSessionName = "NetProviderSession", DurationSeconds = DefaultDurationSeconds }; var credentials = (await sts.AssumeRoleWithWebIdentityAsync(assumeRequest).ConfigureAwait(false)).Credentials; // Return new refresh state (credentials and expiration) credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration); return credentialsState; }