Container for the parameters to the GetId operation. Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.

This is a public API. You do not need any credentials to call this API.

Inheritance: AmazonCognitoIdentityRequest
Exemple #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;
            }
        }
Exemple #2
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);
        }
        /// <summary>
        /// Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit
        /// linked account.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetId service method.</param>
        /// 
        /// <returns>The response from the GetId service method, as returned by CognitoIdentity.</returns>
        /// <exception cref="Amazon.CognitoIdentity.Model.InternalErrorException">
        /// Thrown when the service encounters an error during processing the request.
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.InvalidParameterException">
        /// Thrown for missing or bad input parameter(s).
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.LimitExceededException">
        /// Thrown when the total number of user pools has exceeded a preset limit.
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.NotAuthorizedException">
        /// Thrown when a user is not authorized to access the requested resource.
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.ResourceConflictException">
        /// Thrown when a user tries to use a login which is already linked to another account.
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.ResourceNotFoundException">
        /// Thrown when the requested resource (for example, a dataset or record) does not exist.
        /// </exception>
        /// <exception cref="Amazon.CognitoIdentity.Model.TooManyRequestsException">
        /// Thrown when a request is throttled.
        /// </exception>
        internal GetIdResponse GetId(GetIdRequest request)
        {
            var marshaller = new GetIdRequestMarshaller();
            var unmarshaller = GetIdResponseUnmarshaller.Instance;

            return Invoke<GetIdRequest,GetIdResponse>(request, marshaller, unmarshaller);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the GetId operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the GetId operation on AmazonCognitoIdentityClient.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void GetIdAsync(GetIdRequest request, AmazonServiceCallback<GetIdRequest, GetIdResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new GetIdRequestMarshaller();
     var unmarshaller = GetIdResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<GetIdRequest,GetIdResponse> responseObject 
                     = new AmazonServiceResult<GetIdRequest,GetIdResponse>((GetIdRequest)req, (GetIdResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<GetIdRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
        /// <summary>
        /// Initiates the asynchronous execution of the GetId operation.
        /// <seealso cref="Amazon.CognitoIdentity.IAmazonCognitoIdentity.GetId"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetId operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public Task<GetIdResponse> GetIdAsync(GetIdRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetIdRequestMarshaller();
            var unmarshaller = GetIdResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, GetIdRequest, GetIdResponse>(request, marshaller, unmarshaller, signer, cancellationToken);
        }
        /// <summary>
        /// Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit
        /// linked account.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetId service method.</param>
        /// 
        /// <returns>The response from the GetId service method, as returned by CognitoIdentity.</returns>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.InternalErrorException">
        /// Thrown when the service encounters an error during processing the request.
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.InvalidParameterException">
        /// Thrown for missing or bad input parameter(s).
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.LimitExceededException">
        /// Thrown when the total number of user pools has exceeded a preset limit.
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.NotAuthorizedException">
        /// Thrown when a user is not authorized to access the requested resource.
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.ResourceConflictException">
        /// Thrown when a user tries to use a login which is already linked to another account.
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.ResourceNotFoundException">
        /// Thrown when the requested resource (for example, a dataset or record) does not exist.
        /// </exception>
        /// <exception cref="T:Amazon.CognitoIdentity.Model.TooManyRequestsException">
        /// Thrown when a request is throttled.
        /// </exception>
		public GetIdResponse GetId(GetIdRequest request)
        {
            var task = GetIdAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
        /// <summary>
        /// Gets the Identity Id corresponding to the credentials retrieved from Cognito.
        /// Note: this setting may change during execution. To be notified of its
        /// new value, attach a listener to IdentityChangedEvent
        /// </summary>
        public async System.Threading.Tasks.Task<string> GetIdentityIdAsync()
        {
            if (!IsIdentitySet)
            {
                var cachedIdentityId = this.GetCachedIdentityId();
                if (string.IsNullOrEmpty(cachedIdentityId))
                {
                    var getIdRequest = new GetIdRequest
                    {
                        AccountId = AccountId,
                        IdentityPoolId = IdentityPoolId,
                        Logins = Logins
                    };

                    var getIdResult = await cib.GetIdAsync(getIdRequest);

                    UpdateIdentity(getIdResult.IdentityId, true);
                }
                else
                {
                    UpdateIdentity(cachedIdentityId, false);
                }
            }

            return identityId;
        }
        /// <summary>
        /// Gets the Identity Id corresponding to the credentials retrieved from Cognito.
        /// Note: this setting may change during execution. To be notified of its
        /// new value, attach a listener to IdentityChangedEvent
        /// </summary>
        public string GetIdentityId()
        {
            if (!IsIdentitySet)
            {
                var cachedIdentityId = this.GetCachedIdentityId();
                if (string.IsNullOrEmpty(cachedIdentityId))
                {
                    var getIdRequest = new GetIdRequest
                    {
                        AccountId = AccountId,
                        IdentityPoolId = IdentityPoolId,
                        Logins = Logins
                    };
#if BCL
                    var response = cib.GetId(getIdRequest);
#else
                    var response = Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync<GetIdResponse>(() => cib.GetIdAsync(getIdRequest));
#endif

                    UpdateIdentity(response.IdentityId, true);
                }
                else
                {
                    UpdateIdentity(cachedIdentityId, false);
                }
            }

            return identityId;
        }
        /// <summary>
        /// Gets the Identity Id corresponding to the credentials retrieved from Cognito.
        /// Note: this setting may change during execution. To be notified of its
        /// new value, attach a listener to IdentityChangedEvent
        /// </summary>
        public async System.Threading.Tasks.Task<string> GetIdentityIdAsync()
        {
            if (!IsIdentitySet)
            {
                var getIdRequest = new GetIdRequest
                {
                    AccountId = AccountId,
                    IdentityPoolId = IdentityPoolId,
                    Logins = Logins
                };

                var getIdResult = await cib.GetIdAsync(getIdRequest);

                UpdateIdentity(getIdResult.IdentityId, true);
            }

            return identityId;
        }
        /// <summary>
        /// Initiates the asynchronous execution of the GetId operation.
        /// <seealso cref="Amazon.CognitoIdentity.IAmazonCognitoIdentity"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetId operation on AmazonCognitoIdentityClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetId
        ///         operation.</returns>
        public IAsyncResult BeginGetId(GetIdRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new GetIdRequestMarshaller();
            var unmarshaller = GetIdResponseUnmarshaller.Instance;

            return BeginInvoke<GetIdRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the GetId operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetId operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<GetIdResponse> GetIdAsync(GetIdRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetIdRequestMarshaller();
            var unmarshaller = GetIdResponseUnmarshaller.Instance;

            return InvokeAsync<GetIdRequest,GetIdResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
 /// <summary>
 /// Provides a way to override fetching the identity in case of developer authenticated identities.
 /// The default behaviour will be using Cognito to retrieve the identity id.
 /// </summary>
 /// <returns>returns a <see cref="IdentityState"/></returns>
 public virtual async System.Threading.Tasks.Task<IdentityState> RefreshIdentityAsync()
 {
     bool isCached = true;
     if (!IsIdentitySet)
     {
         var getIdRequest = new GetIdRequest
         {
             AccountId = AccountId,
             IdentityPoolId = IdentityPoolId,
             Logins = Logins
         };
         var response = await cib.GetIdAsync(getIdRequest).ConfigureAwait(false);
         isCached = false;
         UpdateIdentity(response.IdentityId);
     }
     return new IdentityState(identityId, isCached);
 }
        /// <summary>
        /// Provides a way to override fetching the identity in case of developer authenticated identities.
        /// The default behaviour will be using Cognito to retrieve the identity id.
        /// </summary>
        /// <returns>returns a <see cref="IdentityState"/></returns>
        protected virtual IdentityState RefreshIdentity()
        {
            bool isCached = true;
            if (!IsIdentitySet)
            {
                var getIdRequest = new GetIdRequest
                {
                    AccountId = AccountId,
                    IdentityPoolId = IdentityPoolId,
                    Logins = Logins
                };
#if BCL
                var response = cib.GetId(getIdRequest);
#else
                var response = Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync<GetIdResponse>(() => cib.GetIdAsync(getIdRequest));
#endif
                isCached = false;
                UpdateIdentity(response.IdentityId);
            }
            return new IdentityState(identityId, isCached);
        }
        IAsyncResult invokeGetId(GetIdRequest request, AsyncCallback callback, object state, bool synchronized)
        {
            var marshaller = new GetIdRequestMarshaller();
            var unmarshaller = GetIdResponseUnmarshaller.Instance;

            return Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the GetId operation.
 /// <seealso cref="Amazon.CognitoIdentity.IAmazonCognitoIdentity"/>
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the GetId operation on AmazonCognitoIdentityClient.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetId
 ///         operation.</returns>
 public IAsyncResult BeginGetId(GetIdRequest request, AsyncCallback callback, object state)
 {
     return invokeGetId(request, callback, state, false);
 }
 /// <summary>
 /// Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit
 /// linked account.
 /// </summary>
 /// <param name="request">Container for the necessary parameters to execute the GetId service method.</param>
 /// 
 /// <returns>The response from the GetId service method, as returned by CognitoIdentity.</returns>
 /// <exception cref="InternalErrorException">
 /// Thrown when the service encounters an error during processing the request.
 /// </exception>
 /// <exception cref="InvalidParameterException">
 /// Thrown for missing or bad input parameter(s).
 /// </exception>
 /// <exception cref="LimitExceededException">
 /// Thrown when the total number of user pools has exceeded a preset limit.
 /// </exception>
 /// <exception cref="NotAuthorizedException">
 /// Thrown when a user is not authorized to access the requested resource.
 /// </exception>
 /// <exception cref="ResourceConflictException">
 /// Thrown when a user tries to use a login which is already linked to another account.
 /// </exception>
 /// <exception cref="ResourceNotFoundException">
 /// Thrown when the requested resource (for example, a dataset or record) does not exist.
 /// </exception>
 /// <exception cref="TooManyRequestsException">
 /// Thrown when a request is throttled.
 /// </exception>
 public GetIdResponse GetId(GetIdRequest request)
 {
     IAsyncResult asyncResult = invokeGetId(request, null, null, true);
     return EndGetId(asyncResult);
 }