/// <summary>
        /// Retrieves a set of temporary credentials for the specified role, valid for the specified timespan.
        /// If the SAML authentication data yield more than one role, a valid role name must be specified.
        /// </summary>
        /// <param name="stsClient">The STS client to use when making the AssumeRoleWithSAML request.</param>
        /// <param name="principalAndRoleArns">
        /// The arns of the principal and role as returned in the SAML assertion.
        /// </param>
        /// <param name="duration">The valid timespan for the credentials.</param>
        /// <returns>Temporary session credentials for the specified or default role for the user.</returns>
        public ImmutableCredentials GetRoleCredentials(IAmazonSecurityTokenService stsClient, string principalAndRoleArns, TimeSpan duration)
        {
            string roleArn = null;
            string principalArn = null;

            foreach (var s in RoleSet.Values)
            {
                if (s.Equals(principalAndRoleArns, StringComparison.OrdinalIgnoreCase))
                {
                    var roleComponents = s.Split(',');
                    principalArn = roleComponents.First();
                    roleArn = roleComponents.Last();
                    break;
                }
            }

            if (string.IsNullOrEmpty(roleArn) || string.IsNullOrEmpty(principalArn))
                throw new ArgumentException("Unknown or invalid role specified.");

            var response = stsClient.AssumeRoleWithSAML(new AssumeRoleWithSAMLRequest
            {
                SAMLAssertion = AssertionDocument,
                RoleArn = roleArn,
                PrincipalArn = principalArn,
                DurationSeconds = (int)duration.TotalSeconds
            });

            return response.Credentials.GetCredentials();
        }
Exemple #2
0
        /// <summary>
        /// Retrieves a set of temporary credentials for the specified role, valid for the specified timespan.
        /// If the SAML authentication data yield more than one role, a valid role name must be specified.
        /// </summary>
        /// <param name="stsClient">The STS client to use when making the AssumeRoleWithSAML request.</param>
        /// <param name="principalAndRoleArns">
        /// The arns of the principal and role as returned in the SAML assertion.
        /// </param>
        /// <param name="duration">The valid timespan for the credentials.</param>
        /// <returns>Temporary session credentials for the specified or default role for the user.</returns>
        public ImmutableCredentials GetRoleCredentials(IAmazonSecurityTokenService stsClient, string principalAndRoleArns, TimeSpan duration)
        {
            string roleArn      = null;
            string principalArn = null;

            foreach (var s in RoleSet.Values)
            {
                if (s.Equals(principalAndRoleArns, StringComparison.OrdinalIgnoreCase))
                {
                    var roleComponents = s.Split(',');
                    principalArn = roleComponents.First();
                    roleArn      = roleComponents.Last();
                    break;
                }
            }

            if (string.IsNullOrEmpty(roleArn) || string.IsNullOrEmpty(principalArn))
            {
                throw new ArgumentException("Unknown or invalid role specified.");
            }

            var response = stsClient.AssumeRoleWithSAML(new AssumeRoleWithSAMLRequest
            {
                SAMLAssertion   = AssertionDocument,
                RoleArn         = roleArn,
                PrincipalArn    = principalArn,
                DurationSeconds = (int)duration.TotalSeconds
            });

            return(response.Credentials.GetCredentials());
        }
Exemple #3
0
        public async Task EmittedFactories_PerformAssumeRole_IfArnGiven(
            string roleArn,
            AssumeRoleResponse response,
            Credentials credentials,
            IAmazonSecurityTokenService stsClient
            )
        {
            response.Credentials = credentials;
            stsClient.AssumeRoleAsync(Any <AssumeRoleRequest>()).Returns(response);

            using var generation = await project.GenerateAssembly();

            var(assembly, _) = generation;
            var factoryType = assembly.GetType("Lambdajection.CompilationTests.AmazonFactories.Handler+LambdajectionConfigurator+S3Factory");
            var factory     = (IAwsFactory <IAmazonS3>)Activator.CreateInstance(factoryType !, new object[] { stsClient }) !;
            var result      = await factory.Create(roleArn);

            var credentialsProperty = typeof(AmazonServiceClient).GetProperty("Credentials", BindingFlags.NonPublic | BindingFlags.Instance) !;
            var actualCredentials   = credentialsProperty.GetMethod !.Invoke(result, Array.Empty <object>());

            actualCredentials.Should().BeSameAs(credentials);
            await stsClient.Received().AssumeRoleAsync(Is <AssumeRoleRequest>(req =>
                                                                              req.RoleArn == roleArn
                                                                              ));
        }
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(
            string accountId, string identityPoolId,
            string unAuthRoleArn, string authRoleArn,
            IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(identityPoolId))
            {
                throw new ArgumentNullException("identityPoolId");
            }
            if (cibClient == null)
            {
                throw new ArgumentNullException("cibClient");
            }
            if (stsClient == null)
            {
                throw new ArgumentNullException("stsClient");
            }

            AccountId      = accountId;
            IdentityPoolId = identityPoolId;
            UnAuthRoleArn  = unAuthRoleArn;
            AuthRoleArn    = authRoleArn;
            Logins         = new Dictionary <string, string>(StringComparer.Ordinal);
            cib            = cibClient;
            sts            = stsClient;
        }
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(
            string accountId, string identityPoolId,
            string unAuthRoleArn, string authRoleArn,
            IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(identityPoolId))
            {
                throw new ArgumentNullException("identityPoolId");
            }
            if (cibClient == null)
            {
                throw new ArgumentNullException("cibClient");
            }
            if ((unAuthRoleArn != null || authRoleArn != null) && stsClient == null)
            {
                throw new ArgumentNullException("stsClient");
            }

            AccountId      = accountId;
            IdentityPoolId = identityPoolId;
            UnAuthRoleArn  = unAuthRoleArn;
            AuthRoleArn    = authRoleArn;
            Logins         = new Dictionary <string, string>(StringComparer.Ordinal);
            cib            = cibClient;
            sts            = stsClient;
            //check cache for identity id
            string cachedIdentity = GetCachedIdentityId();

            if (!string.IsNullOrEmpty(cachedIdentity))
            {
                UpdateIdentity(cachedIdentity);
                //update the credentials from cache
                currentState = GetCachedCredentials();
            }
        }
        /// <summary>
        /// Instantiates STSAssumeRoleAWSCredentials which automatically assumes a specified SAML role.
        /// The credentials are refreshed before expiration.
        /// </summary>
        /// <param name="assumeRoleWithSamlRequest">Configuration for the SAML role to assume.</param>
        public STSAssumeRoleAWSCredentials(AssumeRoleWithSAMLRequest assumeRoleWithSamlRequest)
        {
            if (assumeRoleWithSamlRequest == null) throw new ArgumentNullException("assumeRoleWithSamlRequest");

            _stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials());
            _assumeSamlRequest = assumeRoleWithSamlRequest;
            PreemptExpiryTime = _defaultPreemptExpiryTime;
        }
        /// <summary>
        /// Instantiates STSAssumeRoleAWSCredentials which automatically assumes a specified role.
        /// The credentials are refreshed before expiration.
        /// </summary>
        /// <param name="sts">
        /// Instance of IAmazonSecurityTokenService that will be used to make the AssumeRole service call.
        /// </param>
        /// <param name="assumeRoleRequest">Configuration for the role to assume.</param>
        public STSAssumeRoleAWSCredentials(IAmazonSecurityTokenService sts, AssumeRoleRequest assumeRoleRequest)
        {
            if (sts == null) throw new ArgumentNullException("sts");
            if (assumeRoleRequest == null) throw new ArgumentNullException("assumeRoleRequest");

            _stsClient = sts;
            _assumeRequest = assumeRoleRequest;
            PreemptExpiryTime = _defaultPreemptExpiryTime;
        }
        /// <summary>
        /// Retrieves a set of temporary credentials for the specified role, valid for the specified timespan.
        /// If the SAML authentication data yield more than one role, a valid role name must be specified.
        /// </summary>
        /// <param name="stsClient">The STS client to use when making the AssumeRoleWithSAML request.</param>
        /// <param name="principalAndRoleArns">
        /// The arns of the principal and role as returned in the SAML assertion.
        /// </param>
        /// <param name="duration">The valid timespan for the credentials.</param>
        /// <returns>Temporary session credentials for the specified or default role for the user.</returns>
        public SAMLImmutableCredentials GetRoleCredentials(IAmazonSecurityTokenService stsClient, string principalAndRoleArns, TimeSpan duration)
        {
            string roleArn      = null;
            string principalArn = null;

            var swappedPrincipalAndRoleArns = string.Empty;

            if (!string.IsNullOrEmpty(principalAndRoleArns))
            {
                var roleComponents = principalAndRoleArns.Split(',');
                if (roleComponents.Count() != 2)
                {
                    throw new ArgumentException("Unknown or invalid principal and role arns format.");
                }

                swappedPrincipalAndRoleArns = roleComponents.Last() + "," + roleComponents.First();
            }

            foreach (var s in RoleSet.Values)
            {
                if (s.Equals(principalAndRoleArns, StringComparison.OrdinalIgnoreCase) || s.Equals(swappedPrincipalAndRoleArns, StringComparison.OrdinalIgnoreCase))
                {
                    var roleComponents = s.Split(',');
                    if (IsSamlProvider(roleComponents.First()))
                    {
                        //Backwards compatible format -- arn:...:saml-provider/SAML,arn:...:role/RoleName
                        principalArn = roleComponents.First();
                        roleArn      = roleComponents.Last();
                    }
                    else
                    {
                        //Documented format -- arn:...:role/RoleName,arn:...:saml-provider/SAML
                        roleArn      = roleComponents.First();
                        principalArn = roleComponents.Last();
                    }

                    break;
                }
            }

            if (string.IsNullOrEmpty(roleArn) || string.IsNullOrEmpty(principalArn))
            {
                throw new ArgumentException("Unknown or invalid role specified.");
            }

            var response = stsClient.AssumeRoleWithSAML(new AssumeRoleWithSAMLRequest
            {
                SAMLAssertion   = AssertionDocument,
                RoleArn         = roleArn,
                PrincipalArn    = principalArn,
                DurationSeconds = (int)duration.TotalSeconds
            });

            return(new SAMLImmutableCredentials(response.Credentials.GetCredentials(),
                                                response.Credentials.Expiration.ToUniversalTime(),
                                                response.Subject));
        }
        /// <summary>
        /// Instantiates AssumeRoleAWSCredentials which automatically assumes a specified SAML role.
        /// The credentials are refreshed before expiration.
        /// </summary>
        /// <param name="assumeRoleWithSamlRequest">Configuration for the SAML role to assume.</param>
        public AssumeRoleAWSCredentials(AssumeRoleWithSAMLRequest assumeRoleWithSamlRequest)
        {
            if (assumeRoleWithSamlRequest == null)
            {
                throw new ArgumentNullException("assumeRoleWithSamlRequest");
            }

            _stsClient        = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials());
            PreemptExpiryTime = _defaultPreemptExpiryTime;
        }
Exemple #10
0
 public IndexModel(
     ILogger <IndexModel> logger,
     IAmazonSecurityTokenService amazonSecurityTokenService,
     IAmazonQuickSight amazonQuickSight
     )
 {
     _logger = logger;
     _amazonSecurityTokenService = amazonSecurityTokenService;
     _amazonQuickSight           = amazonQuickSight;
 }
 public AwsIdentityCommandClient(
     IAmazonIdentityManagementService client,
     IAmazonSecurityTokenService securityTokenServiceClient,
     IPolicyTemplateRepository policyTemplateRepository,
     IIdentityManagementServiceClient identityManagementClient)
 {
     _client = client;
     _securityTokenServiceClient = securityTokenServiceClient;
     _policyTemplateRepository   = policyTemplateRepository;
     _identityManagementClient   = identityManagementClient;
 }
Exemple #12
0
 /// <summary>
 /// Implements the Dispose pattern
 /// </summary>
 /// <param name="disposing">Whether this object is being disposed via a call to Dispose
 /// or garbage collected.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (!this._isDisposed)
     {
         if (disposing && _stsClient != null)
         {
             _stsClient.Dispose();
             _stsClient = null;
         }
         this._isDisposed = true;
     }
 }
 /// <summary>
 /// Implements the Dispose pattern
 /// </summary>
 /// <param name="disposing">Whether this object is being disposed via a call to Dispose
 /// or garbage collected.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (!this._isDisposed)
     {
         if (disposing && _stsClient != null)
         {
             _stsClient.Dispose();
             _stsClient = null;
         }
         this._isDisposed = true;
     }
 }
 /// <summary>
 /// Instantiates STSAssumeRoleAWSCredentials which automatically assumes a specified role.
 /// The credentials are refreshed before expiration.
 /// </summary>
 /// <param name="sts">
 /// Instance of IAmazonSecurityTokenService that will be used to make the AssumeRole service call.
 /// </param>
 /// <param name="assumeRoleRequest">Configuration for the role to assume.</param>
 public STSAssumeRoleAWSCredentials(IAmazonSecurityTokenService sts, AssumeRoleRequest assumeRoleRequest)
 {
     if (sts == null)
     {
         throw new ArgumentNullException("sts");
     }
     if (assumeRoleRequest == null)
     {
         throw new ArgumentNullException("assumeRoleRequest");
     }
     _stsClient        = sts;
     _assumeRequest    = assumeRoleRequest;
     PreemptExpiryTime = _defaultPreemptExpiryTime;
 }
        public async Task Permissions_ShouldContainGetObject(
            string roleArn,
            AssumeRoleResponse response,
            Credentials credentials,
            IAmazonSecurityTokenService stsClient
            )
        {
            using var generation = await project.GenerateAssembly();

            var iamDocText = await File.ReadAllTextAsync(IamDocPath);

            var permissions = iamDocText.ToString().Split('\n');

            permissions.Should().Contain("s3:GetObject");
        }
Exemple #16
0
        public async Task EmittedFactories_DoNotPerformAssumeRole_IfNoArnGiven(
            IAmazonSecurityTokenService stsClient
            )
        {
            using var generation = await project.GenerateAssembly();

            var(assembly, _) = generation;
            var factoryType = assembly.GetType("Lambdajection.CompilationTests.AmazonFactories.Handler+LambdajectionConfigurator+S3Factory");
            var factory     = (IAwsFactory <IAmazonS3>)Activator.CreateInstance(factoryType !, new object[] { stsClient }) !;

            var result = await factory.Create();

            result.Should().NotBeNull();
            await stsClient.DidNotReceive().AssumeRoleAsync(Any <AssumeRoleRequest>());
        }
Exemple #17
0
        public async Task EmittedFactories_ThrowsIfCancellationRequested(
            IAmazonSecurityTokenService stsClient
            )
        {
            using var generation = await project.GenerateAssembly();

            var(assembly, _) = generation;
            var factoryType = assembly.GetType("Lambdajection.CompilationTests.AmazonFactories.Handler+LambdajectionConfigurator+S3Factory");
            var factory     = (IAwsFactory <IAmazonS3>)Activator.CreateInstance(factoryType !, new object[] { stsClient }) !;

            var         cancellationToken = new CancellationToken(true);
            Func <Task> func = async() => await factory.Create(cancellationToken : cancellationToken);

            await func.Should().ThrowAsync <OperationCanceledException>();

            await stsClient.DidNotReceive().AssumeRoleAsync(Any <AssumeRoleRequest>());
        }
Exemple #18
0
        public async Task GeneratedTemplate_ShouldHaveHandlerRole(
            string roleArn,
            AssumeRoleResponse response,
            Credentials credentials,
            IAmazonSecurityTokenService stsClient
            )
        {
            var deserializer = new DeserializerBuilder()
                               .WithNodeDeserializer(new IntrinsicNodeDeserializer())
                               .WithNodeTypeResolver(new IntrinsicNodeTypeResolver())
                               .Build();

            using var generation = await project.GenerateAssembly();

            var templateText = await File.ReadAllTextAsync(TemplatePath);

            var template = deserializer.Deserialize <dynamic>(templateText.ToString());

            ((string)template["Resources"]["HandlerRole"]["Type"]).Should().Be("AWS::IAM::Role");
        }
Exemple #19
0
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(string unAuthRoleArn, string authRoleArn,
                                     AbstractCognitoIdentityProvider idClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(unAuthRoleArn) && string.IsNullOrEmpty(authRoleArn))
            {
                throw new InvalidOperationException("At least one of unAuthRoleArn or authRoleArn must be specified");
            }
            if (idClient == null)
            {
                throw new ArgumentNullException("idClient");
            }
            if (stsClient == null)
            {
                throw new ArgumentNullException("stsClient");
            }

            UnAuthRoleArn    = unAuthRoleArn;
            AuthRoleArn      = authRoleArn;
            IdentityProvider = idClient;
            sts = stsClient;
        }
Exemple #20
0
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(string unAuthRoleArn, string authRoleArn,
                                     AbstractCognitoIdentityProvider idClient, IAmazonSecurityTokenService stsClient)
        {
            if (idClient == null)
            {
                throw new ArgumentNullException("idClient");
            }

            UnAuthRoleArn    = unAuthRoleArn;
            AuthRoleArn      = authRoleArn;
            IdentityProvider = idClient;
            sts = stsClient;

                        #if UNITY_WEBPLAYER
            _persistentStore = new InMemoryKVStore();
                        #else
            _persistentStore = new SQLiteKVStore();
                        #endif

            //Load cached credentials
            string cachedIdentity = _persistentStore.Get(namespacedKey(ID_KEY));
            if (string.IsNullOrEmpty(cachedIdentity))
            {
                //Try to recover unamespaced identities stored by old versions of the SDK
                cachedIdentity = _persistentStore.Get(ID_KEY);
            }
            if (!string.IsNullOrEmpty(cachedIdentity))
            {
                IdentityProvider.UpdateIdentity(cachedIdentity);
                loadCachedCredentials();
            }

            //Register Identity Changed Listener to update the cache
            IdentityProvider.IdentityChangedEvent += delegate(object sender, IdentityChangedArgs e)
            {
                saveCredentials();
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoAWSCredentials", "Saved identityID to LocalStorage");
            };
        }
Exemple #21
0
        public async Task Role_ShouldNotHaveEmptyPolicy(
            string roleArn,
            AssumeRoleResponse response,
            Credentials credentials,
            IAmazonSecurityTokenService stsClient
            )
        {
            using var generation = await project.GenerateAssembly();

            var templateText = await File.ReadAllTextAsync(TemplatePath);

            var template = new DeserializerBuilder()
                           .WithTagMapping("!GetAtt", typeof(GetAttTag))
                           .WithTagMapping("!Sub", typeof(SubTag))
                           .WithTypeConverter(new GetAttTagConverter())
                           .WithTypeConverter(new SubTagConverter())
                           .Build()
                           .Deserialize <dynamic>(templateText.ToString());

            var props = (Dictionary <object, object>)template["Resources"]["HandlerRole"]["Properties"] !;

            props.Should().NotContainKey("Policies");
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            Client = CreateClient(_CurrentCredentials, _RegionEndpoint);
        }
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(
            string accountId, string identityPoolId,
            string unAuthRoleArn, string authRoleArn,
            IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(identityPoolId)) throw new ArgumentNullException("identityPoolId");
            if (cibClient == null) throw new ArgumentNullException("cibClient");
            if ((unAuthRoleArn != null || authRoleArn != null) && stsClient == null) throw new ArgumentNullException("stsClient");

            AccountId = accountId;
            IdentityPoolId = identityPoolId;
            UnAuthRoleArn = unAuthRoleArn;
            AuthRoleArn = authRoleArn;
            Logins = new Dictionary<string, string>(StringComparer.Ordinal);
            cib = cibClient;
            sts = stsClient;

            //check cache for identity id
            string cachedIdentity = GetCachedIdentityId();

            if (!string.IsNullOrEmpty(cachedIdentity))
            {
                UpdateIdentity(cachedIdentity);
                //update the credentials from cache
                _currentState = GetCachedCredentials();
            }

        }
 /// <summary>
 /// Constructs a new SQLiteCognitoAWSCredentials instance, which will use the
 /// specified Amazon Cognito identity pool to make a requests to the
 /// AWS Security Token Service (STS) to request short lived session credentials.
 /// </summary>
 /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
 /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
 /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
 /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
 /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
 /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
 public SQLiteCognitoAWSCredentials(string accountId, string identityPoolId, string unAuthRoleArn, string authRoleArn, IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
     : base(accountId, identityPoolId, unAuthRoleArn, authRoleArn, cibClient, stsClient) { }
Exemple #25
0
 public TenantSecurity(IAmazonSecurityTokenService sts, ClaimsPrincipal claims)
 {
     _sts    = sts;
     _claims = claims;
 }
Exemple #26
0
 /// <summary>
 /// Constructs a new CognitoAWSCredentials instance, which will use the
 /// specified Amazon Cognito identity pool to make a requests to the
 /// AWS Security Token Service (STS) to request short lived session credentials.
 /// </summary>
 /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
 /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
 /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
 /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
 /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
 /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
 public CachingCognitoAWSCredentials(string unAuthRoleArn, string authRoleArn,
                                     AbstractCognitoIdentityProvider idClient, IAmazonSecurityTokenService stsClient)
     : base(unAuthRoleArn, authRoleArn, idClient, stsClient)
 {
 }
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">>Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(
            string accountId, string identityPoolId,
            string unAuthRoleArn, string authRoleArn,
            IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(identityPoolId)) throw new ArgumentNullException("identityPoolId");
            if (cibClient == null) throw new ArgumentNullException("cibClient");
            if (stsClient == null) throw new ArgumentNullException("stsClient");

            AccountId = accountId;
            IdentityPoolId = identityPoolId;
            UnAuthRoleArn = unAuthRoleArn;
            AuthRoleArn = authRoleArn;
            Logins = new Dictionary<string, string>(StringComparer.Ordinal);
            cib = cibClient;
            sts = stsClient;
        }
Exemple #28
0
 public DotnetCognitoAWSCredentials(string accountId, string identityPoolId, string unAuthRoleArn, string authRoleArn, IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient) : base(accountId, identityPoolId, unAuthRoleArn, authRoleArn, cibClient, stsClient)
 {
 }
 private Amazon.SecurityToken.Model.DecodeAuthorizationMessageResponse CallAWSServiceOperation(IAmazonSecurityTokenService client, Amazon.SecurityToken.Model.DecodeAuthorizationMessageRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Security Token Service (STS)", "DecodeAuthorizationMessage");
     try
     {
         #if DESKTOP
         return(client.DecodeAuthorizationMessage(request));
         #elif CORECLR
         return(client.DecodeAuthorizationMessageAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
Exemple #30
0
        /// <summary>
        /// Constructs an <see cref="AmazonEC2Client" /> instance with the
        /// temporary details generated from role assumption.
        /// </summary>
        /// <param name="explicitCredentials">
        /// An instance of <see cref="AWSCredentials" /> containing explicitly
        /// declared credentials (i.e. from the command line). Can be null.
        /// </param>
        /// <param name="amazonEC2Config">
        /// An instance of <see cref="AmazonEC2Config" />.
        /// </param>
        /// <param name="roleArn">
        /// An IAM role ARN to assume.
        /// </param>
        /// <returns>
        /// A configured instance of <see cref="AmazonEC2Client" />.
        /// </returns>
        private AmazonEC2Client AssumeRoleAndCreateEC2Client(
            AWSCredentials explicitCredentials,
            AmazonEC2Config amazonEC2Config,
            string roleArn)
        {
            AmazonEC2Client toReturn = null;

            AmazonSecurityTokenServiceConfig amazonSecurityTokenServiceConfig =
                new AmazonSecurityTokenServiceConfig()
            {
                // Nothing for now...
            };

            IAmazonSecurityTokenService amazonSecurityTokenService = null;

            // Explcit credentials supplied?
            if (explicitCredentials == null)
            {
                this.loggingProvider.Debug(
                    $"No explicit credentials provided. Creating an " +
                    $"instance of the " +
                    $"{nameof(AmazonSecurityTokenServiceClient)} using " +
                    "credentials stored in the credentials file...");

                // Nope. Use the credentials file.
                amazonSecurityTokenService =
                    new AmazonSecurityTokenServiceClient(
                        amazonSecurityTokenServiceConfig);
            }
            else
            {
                this.loggingProvider.Debug(
                    $"Explicit credentials provided. Creating an instance " +
                    $"of the {nameof(AmazonSecurityTokenServiceClient)} " +
                    $"using these details...");

                // Yep.
                amazonSecurityTokenService =
                    new AmazonSecurityTokenServiceClient(
                        explicitCredentials,
                        amazonSecurityTokenServiceConfig);
            }

            this.loggingProvider.Info(
                $"Instance of {nameof(AmazonSecurityTokenServiceClient)} " +
                $"established.");

            this.loggingProvider.Debug(
                $"Parsing role ARN \"{roleArn}\" to create the session " +
                $"name...");

            // Just use the latter part of the ARN as the session name.
            string roleSessionName = roleArn.Split('/')
                                     .Last();

            this.loggingProvider.Info(
                $"Session name created from ARN: \"{roleSessionName}\".");

            AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            {
                RoleArn         = roleArn,
                RoleSessionName = roleSessionName
            };

            this.loggingProvider.Debug(
                $"Pulling back credentials from " +
                $"{nameof(AmazonSecurityTokenServiceClient)} by assuming " +
                $"specified role...");

            // Get the temporary credentials using the specified role.
            AssumeRoleResponse assumeRoleResponse =
                amazonSecurityTokenService.AssumeRole(assumeRoleRequest);

            Credentials roleCreds = assumeRoleResponse.Credentials;

            this.loggingProvider.Info(
                $"Credentials returned. Access ID: " +
                $"\"{roleCreds.AccessKeyId}\". Returning " +
                $"an instance of {nameof(AmazonEC2Client)}.");

            toReturn = new AmazonEC2Client(
                roleCreds,
                amazonEC2Config);

            return(toReturn);
        }