Пример #1
0
        //public CognitoAWSCredentials GetCachedCognitoIdentity()
        //{
        //    Console.WriteLine("GetCachedCognitoIdentity");
        //    if (!string.IsNullOrEmpty(credentials.GetCachedIdentityId()) || credentials.CurrentLoginProviders.Length > 0)
        //    {
        //        return credentials;
        //    }
        //    return null;
        //}

        public async Task GetAWSCredentialsWithGoogleToken(string token)
        {
            try
            {
                CognitoAWSCredentials credentials = new CognitoAWSCredentials(this.IDENTITYPOOL_ID, RegionEndpoint.EUCentral1);
                credentials.Clear();
                credentials.AddLogin("accounts.google.com", token);

                AmazonCognitoIdentityClient cli = new AmazonCognitoIdentityClient(credentials, RegionEndpoint.EUCentral1);

                var req = new Amazon.CognitoIdentity.Model.GetIdRequest();
                req.Logins.Add("accounts.google.com", token);
                req.IdentityPoolId = this.IDENTITYPOOL_ID;

                GetIdResponse getIdResponse = await cli.GetIdAsync(req);

                var getCredentialReq = new Amazon.CognitoIdentity.Model.GetCredentialsForIdentityRequest();
                getCredentialReq.IdentityId = getIdResponse.IdentityId;
                getCredentialReq.Logins.Add("accounts.google.com", token);

                GetCredentialsForIdentityResponse getCredentialsResponse = await cli.GetCredentialsForIdentityAsync(getCredentialReq);

                UserInfo.Credentials = getCredentialsResponse.Credentials;
                UserInfo.IdentityId  = getCredentialsResponse.IdentityId;
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetAWSCredentialsWithGoogleToken ERROR: " + ex.Message);
                throw ex;
            }
        }
Пример #2
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCognitoIdentityConfig config = new AmazonCognitoIdentityConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCognitoIdentityClient client = new AmazonCognitoIdentityClient(creds, config);

            ListIdentityPoolsResponse resp = new ListIdentityPoolsResponse();

            do
            {
                ListIdentityPoolsRequest req = new ListIdentityPoolsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListIdentityPools(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.IdentityPools)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Пример #3
0
        public async Task <IActionResult> ConnectToAWSViaCognitoCredsAsync()
        {
            try
            {
                if (!this.HttpContext.User.Identity.IsAuthenticated)
                {
                    return(new OkObjectResult("you have to sign in to access AWS resources"));
                }


                AnonymousAWSCredentials cred = new AnonymousAWSCredentials();

                AmazonCognitoIdentityClient cognitoClient = new AmazonCognitoIdentityClient(
                    cred,
                    RegionEndpoint.USEast2
                    );

                GetIdRequest idRequest = new GetIdRequest();
                idRequest.AccountId      = "628654266155";
                idRequest.IdentityPoolId = "us-east-2:c6e1e652-eb33-4daa-a04e-9cb0418a92cc";
                var logins = new Dictionary <string, string> {
                    { "dev-220949.okta.com/oauth2/default", GetOktaTokenMiddleware.OktaToken }
                };
                idRequest.Logins = logins;


                // The identity id is in the IdentityId parameter of the response object
                GetIdResponse idResp = await cognitoClient.GetIdAsync(idRequest);


                //GetCredentialsForIdentityRequest getCredentialsRequest =
                //    new GetCredentialsForIdentityRequest { IdentityId = idResp.IdentityId, Logins = logins };

                var temporaryCreds = await cognitoClient.GetCredentialsForIdentityAsync(idResp.IdentityId, logins);

                //var s3Client = new AmazonS3Client(temporaryCreds.Credentials, RegionEndpoint.USEast2);

                var s3Client = new AmazonS3Client(temporaryCreds.Credentials, RegionEndpoint.USEast2);

                return(await this.ObjectFromBucket(s3Client));

                //var assumeRoleRequest = new AssumeRoleWithWebIdentityRequest
                //{
                //    RoleArn = "arn:aws:iam::628654266155:role/acme_empoyees_accessing_s3",
                //    RoleSessionName = "testsession",
                //    WebIdentityToken = GetOktaTokenMiddleware.OktaToken,
                //};

                //var stsServiceClient = new AmazonSecurityTokenServiceClient(temporaryCreds.Credentials, RegionEndpoint.USEast2);
                //var response = await stsServiceClient.AssumeRoleWithWebIdentityAsync(assumeRoleRequest);

                //return new OkObjectResult($" assumed role is {response.AssumedRoleUser.AssumedRoleId}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #4
0
    // Retrieves credentials for existing identities
    async Task <GetCredentialsForIdentityResponse> GetCredentialsForExistingIdentity(string identity)
    {
        // As this is a public API, we call it with fake access keys
        AmazonCognitoIdentityClient cognitoClient = new AmazonCognitoIdentityClient("A", "B", this.region);
        var resp = await cognitoClient.GetCredentialsForIdentityAsync(identity);

        return(resp);
    }
Пример #5
0
        static private async Task <UserCognitoCredentials> getCognitoCredentials(String userEmail, String userPassword)
        {
            String cognitoUserPoolId     = "us-east-1_n8TiZp7tu";
            String cognitoClientId       = "6clvd0v40jggbaa5qid2h6hkqf";
            String cognitoIdentityPoolId = "us-east-1:bff024bb-06d0-4b04-9e5d-eb34ed07f884";

            Amazon.RegionEndpoint cognitoRegion = Amazon.RegionEndpoint.USEast1;

            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast1);
            CognitoUserPool userPool = new CognitoUserPool(cognitoUserPoolId, cognitoClientId, provider);
            CognitoUser     user     = new CognitoUser(userEmail, cognitoClientId, userPool, provider);

            AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = userPassword
            }).ConfigureAwait(false);

            String accessToken = context.AuthenticationResult.AccessToken;
            String idToken     = context.AuthenticationResult.IdToken;

            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials(cognitoIdentityPoolId, cognitoRegion);

            var identityClient = new AmazonCognitoIdentityClient(credentials, cognitoRegion);
            var idRequest      = new Amazon.CognitoIdentity.Model.GetIdRequest();

            idRequest.IdentityPoolId = cognitoIdentityPoolId;
            idRequest.Logins         = new Dictionary <string, string> {
                { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken }
            };
            var idResponseId = await identityClient.GetIdAsync(idRequest).ConfigureAwait(false);

            if (idResponseId.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseId.HttpStatusCode));
                System.Environment.Exit(1);
            }

            var idResponseCredential = await identityClient.GetCredentialsForIdentityAsync(idResponseId.IdentityId, new Dictionary <string, string> {
                { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken }
            }).ConfigureAwait(false);

            if (idResponseCredential.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseCredential.HttpStatusCode));
                System.Environment.Exit(1);
            }

            var cognitoCredentials = new UserCognitoCredentials(idResponseCredential.Credentials);

            return(cognitoCredentials);
        }
Пример #6
0
        protected IAmazonCognitoIdentity CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonCognitoIdentityConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonCognitoIdentityClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Пример #7
0
        /// <summary>
        /// Initializes a new MIC client instance using the specified
        /// MIC Manifest document.
        /// </summary>
        /// <param name="manifest"></param>
        protected MicClient(MicManifest manifest) : base()
        {
            Manifest = manifest ?? throw new ArgumentNullException(nameof(manifest));

            Config = new MicClientConfig()
            {
                RegionEndpoint = Manifest.AwsRegion
            };

            var anonymousCreds = new AnonymousAWSCredentials();

            cognitoClient = new AmazonCognitoIdentityClient(anonymousCreds, Config.Create <AmazonCognitoIdentityConfig>());
            stsClient     = new AmazonSecurityTokenServiceClient(anonymousCreds, Config.Create <AmazonSecurityTokenServiceConfig>());

            AwsCredentials = new CognitoAWSCredentials(accountId: null, identityPoolId: Manifest.IdentityPool,
                                                       unAuthRoleArn: null, authRoleArn: null,
                                                       cognitoClient, stsClient
                                                       );
        }
Пример #8
0
        //Tests GetCognitoAWSCredentials
        public async void TestGetCognitoAWSCredentials()
        {
            string password     = "******";
            string poolRegion   = user.UserPool.PoolID.Substring(0, user.UserPool.PoolID.IndexOf("_"));
            string providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + user.UserPool.PoolID;

            AuthFlowResponse context =
                await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            //Create identity pool
            identityClient = new AmazonCognitoIdentityClient(clientCredentials, clientRegion);
            CreateIdentityPoolResponse poolResponse =
                await identityClient.CreateIdentityPoolAsync(new CreateIdentityPoolRequest()
            {
                AllowUnauthenticatedIdentities = false,
                CognitoIdentityProviders       = new List <CognitoIdentityProviderInfo>()
                {
                    new CognitoIdentityProviderInfo()
                    {
                        ProviderName = providerName, ClientId = user.ClientID
                    }
                },
                IdentityPoolName = "TestIdentityPool" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).ConfigureAwait(false);

            identityPoolId = poolResponse.IdentityPoolId;

            //Create role for identity pool
            managementClient = new AmazonIdentityManagementServiceClient(clientCredentials, clientRegion);
            CreateRoleResponse roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = "_TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                AssumeRolePolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect" +
                                           "\": \"Allow\",\"Principal\": {\"Federated\": \"cognito-identity.amazonaws.com\"}," +
                                           "\"Action\": \"sts:AssumeRoleWithWebIdentity\"}]}"
            }).Result;

            roleName = roleResponse.Role.RoleName;

            //Create and attach policy for role
            CreatePolicyResponse policyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest()
            {
                PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": " +
                                 "[{\"Effect\": \"Allow\",\"Action\": [\"mobileanalytics:PutEvents\",\"cog" +
                                 "nito-sync:*\",\"cognito-identity:*\",\"s3:*\"],\"Resource\": [\"*\"]}]}",
                PolicyName = "_Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).Result;

            policyArn = policyResponse.Policy.Arn;

            AttachRolePolicyRequest attachRequest = new AttachRolePolicyRequest()
            {
                PolicyArn = policyArn,
                RoleName  = roleName
            };
            AttachRolePolicyResponse attachRolePolicyResponse = managementClient.AttachRolePolicyAsync(attachRequest).Result;

            //Set the role for the identity pool
            await identityClient.SetIdentityPoolRolesAsync(new SetIdentityPoolRolesRequest()
            {
                IdentityPoolId = identityPoolId,
                Roles          = new Dictionary <string, string>()
                {
                    { "authenticated", roleResponse.Role.Arn },
                    { "unauthenticated", roleResponse.Role.Arn }
                },
            }).ConfigureAwait(false);

            //Create and test credentials
            CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials(identityPoolId, clientRegion);

            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1))
            {
                int tries = 0;
                ListBucketsResponse bucketsResponse = null;
                var       retryLimit    = 5;
                Exception lastException = null;

                for (; tries < retryLimit; tries++)
                {
                    try
                    {
                        bucketsResponse = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                        Assert.Equal(bucketsResponse.HttpStatusCode, System.Net.HttpStatusCode.OK);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                        System.Threading.Thread.Sleep(3000);
                    }
                }

                if (tries == retryLimit && lastException != null)
                {
                    throw lastException;
                }
            }
        }
        public ActionResult Browse()
        {
            List <Models.S3File> files = new List <Models.S3File>();

            strCurrentUsername = HttpContext.User.Identity.Name;

            if (!string.IsNullOrEmpty(strCurrentUsername))
            {
                if (strCurrentUsername.EndsWith("workerbee.com"))
                {
                    strUserCognitoPoolId = strWorkerBeeCognitoPoolId;
                }
                else if (strCurrentUsername.EndsWith("queenbee.com"))
                {
                    strUserCognitoPoolId = strQueenBeeCognitoPoolId;
                }
                else if (strCurrentUsername.EndsWith("beehive.com"))
                {
                    strUserCognitoPoolId = strBeeHiveCognitoPoolId;
                }
                else //any other email domain
                {
                    strUserCognitoPoolId = strFreeBeeCognitoPoolId;
                }
            }

            Amazon.RegionEndpoint northVirginiaRegion = Amazon.RegionEndpoint.USEast1; //Virginia location


            string strAccessKeyId     = ConfigurationManager.AppSettings["CognitoDeveloperAccessKeyId"];
            string strAccessKeySecret = ConfigurationManager.AppSettings["CognitoDeveloperAccessKeySecret"];


            AmazonCognitoIdentityClient cognitoIdClient = new AmazonCognitoIdentityClient(strAccessKeyId, strAccessKeySecret, northVirginiaRegion);

            if (cognitoIdClient != null)
            {
                Dictionary <string, string> customLogin = new Dictionary <string, string>();
                customLogin.Add(DEVELOPER_PROVIDER_NAME, HttpContext.User.Identity.Name);
                GetOpenIdTokenForDeveloperIdentityRequest oidcTokenReq = new GetOpenIdTokenForDeveloperIdentityRequest();
                //oidcTokenReq.IdentityId = HttpContext.User.Identity.Name;
                oidcTokenReq.IdentityPoolId = strUserCognitoPoolId;
                oidcTokenReq.TokenDuration  = 86400; //24hr for ID token validaty
                oidcTokenReq.Logins         = customLogin;


                //Get an OpenID Connect token from AWS Cognito
                GetOpenIdTokenForDeveloperIdentityResponse oidcTokenRes = cognitoIdClient.GetOpenIdTokenForDeveloperIdentity(oidcTokenReq);

                //Get the Cognito Identity ID for the current user
                GetCredentialsForIdentityRequest credentialsForIdReq = new GetCredentialsForIdentityRequest()
                {
                    IdentityId = oidcTokenRes.IdentityId,
                    //Logins = customLogin
                };


                Dictionary <string, string> token = new Dictionary <string, string>();
                token.Add("cognito-identity.amazonaws.com", oidcTokenRes.Token);//

                //Get the token from AWS STS (through AWS Cognito) to assume an AWS role that will allow to user to query AWS S3
                GetCredentialsForIdentityResponse credentialsForIdRes = cognitoIdClient.GetCredentialsForIdentity(oidcTokenRes.IdentityId, token);
                Credentials awsCreds = credentialsForIdRes.Credentials;

                using (var s3Client = new AmazonS3Client(awsCreds, northVirginiaRegion))
                {
                    try
                    {
                        var             bucketsRes = s3Client.ListBuckets();
                        List <S3Bucket> buckets    = bucketsRes.Buckets;

                        foreach (S3Bucket bucket in buckets)
                        {
                            try
                            {
                                ListObjectsResponse listObjectsRes = s3Client.ListObjects(bucket.BucketName);
                                List <S3Object>     s3Objects      = listObjectsRes.S3Objects;
                                foreach (S3Object s3file in s3Objects)
                                {
                                    files.Add(new Models.S3File()
                                    {
                                        FileName = s3file.Key
                                    });
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    catch (AmazonCognitoIdentityException cex)
                    {
                        string strError = cex.ToString();
                    }
                    catch (Exception ex)
                    {
                        ////throw;
                    }
                }
            }

            return(View(files));
        }
        //Tests GetCognitoAWSCredentials
        public async void TestGetCognitoAWSCredentials()
        {
            var password     = "******";
            var poolRegion   = user.UserPool.PoolID.Substring(0, user.UserPool.PoolID.IndexOf("_", StringComparison.Ordinal));
            var providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + user.UserPool.PoolID;

            var context =
                await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            //Create identity pool
            identityClient = new AmazonCognitoIdentityClient(clientCredentials, clientRegion);
            var poolResponse =
                await identityClient.CreateIdentityPoolAsync(new CreateIdentityPoolRequest()
            {
                AllowUnauthenticatedIdentities = false,
                CognitoIdentityProviders       = new List <CognitoIdentityProviderInfo>()
                {
                    new CognitoIdentityProviderInfo()
                    {
                        ProviderName = providerName, ClientId = user.ClientID
                    }
                },
                IdentityPoolName = "TestIdentityPool" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).ConfigureAwait(false);

            identityPoolId = poolResponse.IdentityPoolId;

            //Create role for identity pool
            managementClient = new AmazonIdentityManagementServiceClient(clientCredentials, clientRegion);
            var roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = "_TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                AssumeRolePolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect" +
                                           "\": \"Allow\",\"Principal\": {\"Federated\": \"cognito-identity.amazonaws.com\"}," +
                                           "\"Action\": \"sts:AssumeRoleWithWebIdentity\"}]}"
            }).Result;

            roleName = roleResponse.Role.RoleName;

            //Create and attach policy for role
            var policyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest()
            {
                PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": " +
                                 "[{\"Effect\": \"Allow\",\"Action\": [\"mobileanalytics:PutEvents\",\"cog" +
                                 "nito-sync:*\",\"cognito-identity:*\",\"s3:*\"],\"Resource\": [\"*\"]}]}",
                PolicyName = "_Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).Result;

            policyArn = policyResponse.Policy.Arn;

            var attachRequest = new AttachRolePolicyRequest()
            {
                PolicyArn = policyArn,
                RoleName  = roleName
            };
            var attachRolePolicyResponse = managementClient.AttachRolePolicyAsync(attachRequest).Result;

            //Set the role for the identity pool
            await identityClient.SetIdentityPoolRolesAsync(new SetIdentityPoolRolesRequest()
            {
                IdentityPoolId = identityPoolId,
                Roles          = new Dictionary <string, string>()
                {
                    { "authenticated", roleResponse.Role.Arn },
                    { "unauthenticated", roleResponse.Role.Arn }
                },
            }).ConfigureAwait(false);

            //Create and test credentials
            var credentials = user.GetCognitoAWSCredentials(identityPoolId, clientRegion);

            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1))
            {
                var tries       = 0;
                var bufferExMsg = "Invalid identity pool configuration. Check assigned IAM roles for this pool.";
                ListBucketsResponse bucketsResponse = null;

                for (; tries < 5; tries++)
                {
                    try
                    {
                        bucketsResponse = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                        break;
                    }
                    catch (NullReferenceException)
                    {
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch (Exception ex)
                    {
                        if (string.Equals(bufferExMsg, ex.Message))
                        {
                            System.Threading.Thread.Sleep(3000);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }

                Assert.True(tries < 5, "Failed to list buckets after 5 tries");
                Assert.Equal(bucketsResponse.HttpStatusCode, System.Net.HttpStatusCode.OK);
            }
        }