// Called when Start game button is clicked void StartGame() { if (!this.gameStartRequested) { this.startGameButton.gameObject.SetActive(false); this.gameStartRequested = true; FindObjectOfType <UIManager>().SetTextBox("Setting up Client.."); // Get the Region enum from the string value this.region = Amazon.RegionEndpoint.GetBySystemName(regionString); Debug.Log("My Region endpoint: " + this.region); // Check if we have stored an identity and request credentials for that existing identity Client.cognitoID = PlayerPrefs.GetString("CognitoID", null); if (Client.cognitoID != null && Client.cognitoID != "") { Debug.Log("Requesting credentials for existing identity: " + Client.cognitoID); var response = Task.Run(() => GetCredentialsForExistingIdentity(Client.cognitoID)); response.Wait(5000); Client.cognitoID = response.Result.IdentityId; Client.cognitoCredentials = new Amazon.Runtime.ImmutableCredentials(response.Result.Credentials.AccessKeyId, response.Result.Credentials.SecretKey, response.Result.Credentials.SessionToken); } // Else get a new identity else { Debug.Log("Requesting a new playeridentity as none stored yet."); CognitoAWSCredentials credentials = new CognitoAWSCredentials( this.identityPoolID, this.region); Client.cognitoCredentials = credentials.GetCredentials(); Client.cognitoID = credentials.GetIdentityId(); Debug.Log("Got Cognito ID: " + credentials.GetIdentityId()); // Store to player prefs and save for future games PlayerPrefs.SetString("CognitoID", Client.cognitoID); PlayerPrefs.Save(); } // Get latencies to regions this.MeasureLatencies(); // Connect to the server now that we have our identity, credendtials and latencies StartCoroutine(ConnectToServer()); } }
private static CognitoAWSCredentials GetCognitoCredentials(string poolId, bool usePoolRoles) { // If using pool roles, no need to prepare a role string roleArn = usePoolRoles ? null : PrepareRole(); var latest = DateTime.Now + roleTimeout; do { CognitoAWSCredentials credentials; if (usePoolRoles) { credentials = new CognitoAWSCredentials(poolId, AWSConfigs.RegionEndpoint); } else { credentials = new CognitoAWSCredentials( null, poolId, roleArn, // The same role is used for unAuthRoleArn roleArn, // and authRoleArn AWSConfigs.RegionEndpoint); } try { credentials.GetCredentials(); return(credentials); } catch (InvalidIdentityPoolConfigurationException iipce) { Assert.IsNotNull(iipce); Assert.AreEqual(invalidPoolConfigurationMessage, iipce.Message); Console.WriteLine("Pool not yet ready, sleeping for " + roleTestPeriod); Thread.Sleep(roleTestPeriod); } catch (AmazonSecurityTokenServiceException astse) { Assert.IsNotNull(astse); //Assert.AreEqual(notAuthorizedMessage, astse.Message); Console.WriteLine("Role not yet ready, sleeping for " + roleTestPeriod); Thread.Sleep(roleTestPeriod); } } while (DateTime.Now < latest); throw new InvalidOperationException("Role should have been ready by now"); }
// calls our game service Lambda function to get connection info for the Realtime server private void ConnectToGameLiftServer() { Debug.Log("Reaching out to client service Lambda function"); AWSConfigs.AWSRegion = "us-east-1"; // Your region here AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; // paste this in from the Amazon Cognito Identity Pool console CognitoAWSCredentials credentials = new CognitoAWSCredentials( "us-east-1:a00a0aa0-a000-0000-0aa0-0aa00a0009a0", // Your identity pool ID here RegionEndpoint.USEast1 // Your region here ); AmazonLambdaClient client = new AmazonLambdaClient(credentials, RegionEndpoint.USEast1); InvokeRequest request = new InvokeRequest { FunctionName = "ConnectClientToServer", InvocationType = InvocationType.RequestResponse }; client.InvokeAsync(request, (response) => { if (response.Exception == null) { if (response.Response.StatusCode == 200) { var payload = Encoding.ASCII.GetString(response.Response.Payload.ToArray()) + "\n"; var playerSessionObj = JsonUtility.FromJson <PlayerSessionObject>(payload); if (playerSessionObj.FleetId == null) { Debug.Log($"Error in Lambda: {payload}"); } else { QForMainThread(ActionConnectToServer, playerSessionObj.IpAddress, Int32.Parse(playerSessionObj.Port), playerSessionObj.PlayerSessionId); } } } else { Debug.LogError(response.Exception); } }); }
private void SetupAWSCredentials() { // 初始化 Amazon Cognito 凭证提供程序 CognitoAWSCredentials credentials = new CognitoAWSCredentials( "us-east-1:be56bffa-67eb-40f0-b7cf-18caf9df0a20", // 身份池 ID RegionEndpoint.USEast1 // 区域 ); this.s3client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);//new AmazonS3Client("your awsAccessKeyId", "your awsSecretKeyId", RegionEndpoint.USEast1); var config = new AmazonS3Config() { RegionEndpoint = Amazon.RegionEndpoint.USEast1, Timeout = TimeSpan.FromSeconds(30), UseHttp = true }; AWSConfigsS3.UseSignatureVersion4 = true; this.s3transferUtility = new TransferUtility(s3client); }
public void ConnectToGameLiftServer() { Debug.Log("Reaching out to client service Lambda function"); AWSConfigs.AWSRegion = "EUCentral1"; AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; // paste this in from the Amazon Cognito Identity Pool console CognitoAWSCredentials credentials = new CognitoAWSCredentials( // die der GameLift-Instanz ist arn:aws:gamelift:eu-central-1:289499586032:fleet/fleet-2f620a33-1536-4732-afb9-a1d1fe7f390e "eu-central-1:60219201-5b2b-4a81-a80b-8ddaf311d0be", RegionEndpoint.EUCentral1); // Region is EUCentral1 AmazonLambdaClient client = new AmazonLambdaClient(credentials, RegionEndpoint.EUCentral1); InvokeRequest request = new InvokeRequest { //FunctionName = "InvokeAsync",//name of lambda function //Dem Lambda-Skript muss mittels Query-String das Spiel mitgeteilt werden ("game" = "SSPS" oder "M3") FunctionName = "matchmaker", InvocationType = InvocationType.RequestResponse, Payload = "{\"queryStringParameters\":{\"game\":\"M3\"}}" }; //create gameLift session client.InvokeAsync(request, (response) => { if (response.Exception == null) { if (response.Response.StatusCode == 200) { var payload = Encoding.ASCII.GetString(response.Response.Payload.ToArray()) + "\n"; var playerSessionObj = JsonUtility.FromJson <PlayerSessionObject>(payload); if (playerSessionObj.FleetId == null) { Debug.Log($"Error in Lambda: {payload}"); } else { //connect JoinMatch(playerSessionObj.IpAddress, playerSessionObj.Port, playerSessionObj.PlayerSessionId); } } } }); }
protected override void Awake() { Application.targetFrameRate = 60; Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None); base.Awake(); _options = CommandLineOptions.Load( CommandLineOptionsJsonPath ); #if !UNITY_EDITOR // FIXME 이후 사용자가 원치 않으면 정보를 보내지 않게끔 해야 합니다. Mixpanel.SetToken("80a1e14b57d050536185c7459d45195a"); if (!(_options.PrivateKey is null)) { var privateKey = new PrivateKey(ByteUtil.ParseHex(_options.PrivateKey)); Address address = privateKey.ToAddress(); Mixpanel.Identify(address.ToString()); } Mixpanel.Init(); Mixpanel.Track("Unity/Started"); #endif if (_options.RpcClient) { Agent = GetComponent <RPCAgent>(); SubscribeRPCAgent(); } else { Agent = GetComponent <Agent>(); } States = new States(); LocalLayer = new LocalLayer(); MainCanvas.instance.InitializeIntro(); #if !UNITY_EDITOR var c = new CognitoAWSCredentials("ap-northeast-2:6fea0e84-a609-4774-a407-c63de9dbea7b", RegionEndpoint.APNortheast2); _logsClient = new AmazonCloudWatchLogsClient(c, RegionEndpoint.APNortheast2); Application.logMessageReceivedThreaded += UploadLog; #endif }
public DB() { // Connect to DynamoDB CognitoAWSCredentials credentials = new CognitoAWSCredentials( AWS.IdentityPoolId, // Your identity pool ID Amazon.RegionEndpoint.USEast1 // Region ); // Create a DynamoDB context try { var client = new AmazonDynamoDBClient(credentials, Amazon.RegionEndpoint.USEast1); this.context = new DynamoDBContext(client); } catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void Awake() { if (string.IsNullOrEmpty(m_identityPoolId)) { Status = LoginStatus.Uninitialized; return; } m_credentials = new CognitoAWSCredentials(m_identityPoolId, AWSRegionHelpers.GetByEnum(m_region)); m_credentials.IdentityChangedEvent += HandleIdentityChangedEvent; string key = COGNITO_GUESTNAMES_CACHE_KEY + ":" + m_identityPoolId; m_guestIdCache = new GuestIdCache(key); m_guestIdCache.RetrieveGuestIds(); Logout(); }
public CognitoSyncManager(CognitoAWSCredentials cognitoCredentials, AmazonCognitoSyncConfig config) { if (cognitoCredentials == null) { throw new ArgumentNullException("cognitoCredentials"); } if (string.IsNullOrEmpty(cognitoCredentials.IdentityPoolId)) { throw new ArgumentNullException("cognitoCredentials.IdentityPoolId"); } this.cognitoCredentials = cognitoCredentials; Local = new SQLiteLocalStorage(System.IO.Path.Combine(Application.persistentDataPath, DATABASE_NAME)); remote = new CognitoSyncStorage(cognitoCredentials, config); cognitoCredentials.IdentityChangedEvent += this.IdentityChanged; _logger = Logger.GetLogger(this.GetType()); }
public async Task ReadObjectDataAsync(string bucket, string objectKey, CognitoAWSCredentials cred) { IAmazonS3 client = null; if (cred != null) { client = new AmazonS3Client(cred, bucketRegion); } else { client = new AmazonS3Client(bucketRegion); } string responseBody = ""; try { GetObjectRequest request = new GetObjectRequest { BucketName = bucket, Key = objectKey }; using (GetObjectResponse response = await client.GetObjectAsync(request)) using (Stream responseStream = response.ResponseStream) using (StreamReader reader = new StreamReader(responseStream)) { string title = response.Metadata["x-amz-meta-title"]; // Assume you have "title" as medata added to the object. string contentType = response.Headers["Content-Type"]; Console.WriteLine("Object metadata, Title: {0}", title); Console.WriteLine("Content type: {0}", contentType); responseBody = reader.ReadToEnd(); // Now you process the response body. Console.WriteLine("Content : {0}", responseBody); } } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } }
public async Task <bool> Login(string email, string password) { // Debug.Log("Login: "******", " + password); CognitoUserPool userPool = new CognitoUserPool(userPoolId, AppClientID, _provider); CognitoUser user = new CognitoUser(email, AppClientID, userPool, _provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = password }; try { AuthFlowResponse authFlowResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); _userid = await GetUserIdFromProvider(authFlowResponse.AuthenticationResult.AccessToken); // Debug.Log("Users unique ID from cognito: " + _userid); UserSessionCache userSessionCache = new UserSessionCache( authFlowResponse.AuthenticationResult.IdToken, authFlowResponse.AuthenticationResult.AccessToken, authFlowResponse.AuthenticationResult.RefreshToken, _userid); SaveDataManager.SaveJsonData(userSessionCache); // This how you get credentials to use for accessing other services. // This IdentityPool is your Authorization, so if you tried to access using an // IdentityPool that didn't have the policy to access your target AWS service, it would fail. _cognitoAWSCredentials = user.GetCognitoAWSCredentials(IdentityPool, Region); _user = user; return(true); } catch (Exception e) { Debug.Log("Login failed, exception: " + e); return(false); } }
// Use this for initialization void Start() { #if UNITY_EDITOR /// This is just to spoof the application to think that its running on iOS platform AmazonHookedPlatformInfo.Instance.Platform = "iPhoneOS"; AmazonHookedPlatformInfo.Instance.Model = "iPhone"; AmazonHookedPlatformInfo.Instance.Make = "Apple"; AmazonHookedPlatformInfo.Instance.Locale = "en_US"; AmazonHookedPlatformInfo.Instance.PlatformVersion = "8.1.2"; AmazonHookedPlatformInfo.Instance.Title = "YourApp"; AmazonHookedPlatformInfo.Instance.VersionName = "v1.0"; AmazonHookedPlatformInfo.Instance.VersionCode = "1.0"; AmazonHookedPlatformInfo.Instance.PackageName = "com.yourcompany.yourapp"; #endif _credentials = new CognitoAWSCredentials(IdentityPoolId, Amazon.RegionEndpoint.USEast1); analyticsManager = MobileAnalyticsManager.GetOrCreateInstance(_credentials, Amazon.RegionEndpoint.USEast1, appId); }
private async void BtnSignIn_ClickAsync(object sender, EventArgs e) { try { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), wwRegion); CognitoUserPool userPool = new CognitoUserPool(wwUserPoolID, wwAppClientID, provider); CognitoUser user = new CognitoUser(txtID.Text, wwAppClientID, userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = txtPass.Text }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); string accessToken = authResponse.AuthenticationResult.AccessToken; string idToken = authResponse.AuthenticationResult.IdToken; // Amazon Cognito 認証情報プロバイダーを初期化します CognitoAWSCredentials credentials = new CognitoAWSCredentials( wwIdPoolID, // ID プールの ID wwRegion // リージョン ); credentials.AddLogin("cognito-idp.us-east-1.amazonaws.com/" + wwUserPoolID, idToken); // the raw token //↓おまじない string hoge = await credentials.GetIdentityIdAsync(); using (var client = new AmazonS3Client(credentials, wwRegion)) { var listObjectRequest = new ListObjectsRequest(); listObjectRequest.BucketName = wwS3BucketName; var response = await client.ListObjectsAsync(listObjectRequest); //ここでオブジェクトがとれる ; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <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 ); }
static AWSHelper() { var loggingConfig = AWSConfigs.LoggingConfig; loggingConfig.LogMetrics = true; loggingConfig.LogResponses = ResponseLoggingOption.Always; loggingConfig.LogMetricsFormat = LogMetricsFormatOption.JSON; loggingConfig.LogTo = LoggingOptions.SystemDiagnostics; AWSConfigs.AWSRegion = "ap-southeast-1"; AWSConfigsS3.UseSignatureVersion4 = true; Credentials = new CognitoAWSCredentials( "868311720350", "ap-southeast-1:ff736cfc-7e26-4f76-9de8-fb0180e862ea", // Identity pool ID "arn:aws:iam::868311720350:role/Cognito_ZiBaobaoAdventureUnauth_Role", null, RegionEndpoint.APSoutheast1 // Region ); }
/// <summary> /// Creates an instance of CognitoSyncManager using cognito credentials and a configuration object /// <code> /// CognitoSyncManager cognitoSyncManager = new CognitoSyncManager(credentials,new AmazonCognitoSyncConfig { RegionEndpoint = RegionEndpoint.USEAST1}) /// </code> /// </summary> /// <param name="cognitoCredentials"><see cref="Amazon.CognitoIdentity.CognitoAWSCredentials"/></param> /// <param name="config"><see cref="Amazon.CognitoSync.AmazonCognitoSyncConfig"/></param> /// <seealso href="http://docs.aws.amazon.com/cognito/latest/developerguide/synchronizing-data.html#initializing-client">Amazon Cognito Sync Dev. Guide - Initializing Client</seealso> public CognitoSyncManager(CognitoAWSCredentials cognitoCredentials, AmazonCognitoSyncConfig config) { if (cognitoCredentials == null) { throw new ArgumentNullException("cognitoCredentials"); } #if BCL ValidateParameters(); #endif this.CognitoCredentials = cognitoCredentials; Local = new SQLiteLocalStorage(); Remote = new CognitoSyncStorage(CognitoCredentials, config); cognitoCredentials.IdentityChangedEvent += this.IdentityChanged; _logger = Logger.GetLogger(this.GetType()); }
//internal async Task<CognitoUser> ResetPassword(string username) //{ // AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); // CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider); // CognitoUser user = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider); // await user.ForgotPasswordAsync(); // return user; //} //internal async Task<CognitoUser> UpdatePassword(string username, string code, string newpassword) //{ // AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); // CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider); // CognitoUser user = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider); // await user.ConfirmForgotPasswordAsync(code, newpassword); // return user; //} public async Task ValidateUser(string username, string password) { try { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.EUCentral1); CognitoUserPool userPool = new CognitoUserPool(this.USERPOOL_ID, this.CLIENTAPP_ID, provider); CognitoUser user = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest(); authRequest.Password = password; AuthFlowResponse authFlowResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); if (authFlowResponse.AuthenticationResult == null) { throw new Exception("Cognito authentication error"); } GetUserResponse userDetails = await user.GetUserDetailsAsync(); string idtoken = authFlowResponse.AuthenticationResult.IdToken; //CognitoAWSCredentials creds = user.GetCognitoAWSCredentials(this.IDENTITYPOOL_ID, RegionEndpoint.EUCentral1); CognitoAWSCredentials creds = new CognitoAWSCredentials(this.IDENTITYPOOL_ID, RegionEndpoint.EUCentral1); creds.Clear(); //creds.CurrentLoginProviders.SetValue(idtoken, 0); //creds.CurrentLoginProviders.SetValue(idtoken, 1); creds.AddLogin("cognito-idp." + RegionEndpoint.EUCentral1.SystemName + ".amazonaws.com/" + this.USERPOOL_ID, idtoken); UserInfo.Clear(); UserInfo.Credentials = creds; UserInfo.UserId = userDetails.UserAttributes.Find(x => x.Name.ToLower() == "sub").Value; UserInfo.UserName = user.Username; UserInfo.Email = userDetails.UserAttributes.Find(x => x.Name.ToLower() == "email").Value; UserInfo.Picture = "userphoto"; } catch (Exception ex) { Console.WriteLine("ValidateUser ERROR: " + ex.Message); throw ex; } }
public void MultipleIdentityPoolTests() { CreatePool(); Utils.AssertTrue(allPoolIds.Count == 2); var pool1 = allPoolIds[0]; var pool2 = allPoolIds[1]; var cred1 = new CognitoAWSCredentials(pool1, ActualEndpoint); var cred2 = new CognitoAWSCredentials(pool2, ActualEndpoint); string id1 = null, id2 = null; AutoResetEvent ars = new AutoResetEvent(false); cred1.GetIdentityIdAsync((result) => { id1 = result.Response; ars.Set(); }, new Amazon.Runtime.AsyncOptions() { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertFalse(string.IsNullOrEmpty(id1)); cred2.GetIdentityIdAsync((result) => { id2 = result.Response; ars.Set(); }, new Amazon.Runtime.AsyncOptions() { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertFalse(string.IsNullOrEmpty(id2)); Assert.AreNotEqual(id1, id2); cred1.Clear(); Utils.AssertStringIsNullOrEmpty(cred1.GetCachedIdentityId()); cred2.Clear(); cred1.Clear(); }
public DefaultCognitoSyncManager(CognitoAWSCredentials cognitoCredentials, AmazonCognitoSyncConfig config) { if (cognitoCredentials == null) { throw new ArgumentNullException("cognitoCredentials is null"); } if (StringUtils.IsEmpty(cognitoCredentials.IdentityProvider.IdentityPoolId)) { throw new ArgumentException("invalid identity pool id"); } this.cognitoCredentials = cognitoCredentials; #if UNITY_WEBPLAYER local = new InMemoryStorage(); #else local = new SQLiteLocalStorage(System.IO.Path.Combine(AmazonInitializer.persistentDataPath, DATABASE_NAME)); #endif remote = new CognitoSyncStorage(cognitoCredentials, config); //remote.setUserAgent(USER_AGENT); cognitoCredentials.IdentityProvider.IdentityChangedEvent += this.IdentityChanged; }
void InitS3() { // Amazon examples don't include this line. Without it, this throws // "Exception: Main thread has not been set, is the AWSPrefab on the scene?". // According to the issue tracker, AWSPrefab is deprecated, and this is the recommended alternative. UnityInitializer.AttachToGameObject(gameObject); // Amazon examples don't include this line. Without it, this throws // "InvalidOperationException: Cannot override system-specified headers". AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; filePath = Path.GetFullPath(fileName); // Initialize the Amazon Cognito credentials provider credentials = new CognitoAWSCredentials(identityPoolID, RegionEndpoint.USEast2); // Amazon examples don't include second parameter. Without it, this throws // "AmazonClientException: No RegionEndpoint or ServiceURL configured". s3Client = new AmazonS3Client(credentials, region); }
/// <summary> /// Adds login to credentials from Identity Provider /// **Note: This has only been verified with Facebook /// </summary> /// <param name="provider"></param> /// <param name="providerToken"></param> /// <returns></returns> public static Result <bool> AddLoginToCredentials(CredentialsProvider provider, string providerToken) { Result <bool> r = new Result <bool>(); string providerPath = ""; if (CognitoCredentials == null) { CognitoCredentials = new CognitoAWSCredentials(CognitoIdentityPoolId, CognitoEndpoint); } ; switch (provider) { case CredentialsProvider.Amazon: throw new NotImplementedException(); case CredentialsProvider.Cognito: throw new NotImplementedException(); case CredentialsProvider.Facebook: providerPath = "graph.facebook.com"; break; case CredentialsProvider.Google: throw new NotImplementedException(); default: break; } try { CognitoCredentials.AddLogin(providerPath, providerToken); } catch (Exception e) { return(r.AsError(e.Message)); } return(r.AsSuccess(true)); }
public void LoginUser() { try { AmazonCognitoIdentityProviderClient _provider = new AmazonCognitoIdentityProviderClient((AWSCredentials) new AnonymousAWSCredentials(), RegionEndpoint.APSoutheast2); CognitoUserPool pool = new CognitoUserPool(AWS_USER_POOL_ID, AWS_CLIENT_ID, _provider); CognitoUser cognitoUser = new CognitoUser(AWS_Username, AWS_CLIENT_ID, pool, _provider); cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = AWS_Password }).Wait(); COGNITO_USER = cognitoUser; COGNITO_AWS_CREDENTIALS = COGNITO_USER.GetCognitoAWSCredentials(AWS_POOL_ID, AWS_REGION_ENDPOINT); AWS_CREDENTIALS = COGNITO_AWS_CREDENTIALS.GetCredentials(); } catch (Exception ex) { throw ex; } }
public async Task <bool> getCredentials() { var credentials = new CognitoAWSCredentials(Statics.identityPoolID, RegionEndpoint.EUWest2); var providername = $"cognito-idp.{RegionEndpoint.EUWest2.SystemName}.amazonaws.com/{Statics.poolID}"; Console.WriteLine(providername); credentials.AddLogin(providername, Statics.id_token); var creds = await credentials.GetCredentialsAsync(); Statics.creds = creds; Statics.credentials = credentials; Console.WriteLine("log in id::" + credentials); Console.WriteLine(creds); return(true); }
// Use this for initialization void Start() { m_TableLength = 0; UnityInitializer.AttachToGameObject(this.gameObject); var credentials = new CognitoAWSCredentials("us-east-1:4a6bd71a-2349-4b3f-9f10-e2865187b87a", RegionEndpoint.USEast1); AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1); Context = new DynamoDBContext(client); var request = new DescribeTableRequest { TableName = @"AppathonTable" }; client.DescribeTableAsync(request, (result) => { if (result.Exception != null) { Debug.Log(result.Exception); return; } var response = result.Response; TableDescription description = response.Table; Debug.Log("# of items: " + response.Table.ItemCount + "\n"); m_TableLength = (int)response.Table.ItemCount; Debug.Log("Provision Throughput (reads/sec): " + description.ProvisionedThroughput.ReadCapacityUnits + "\n"); //StartCoroutine(CheckTableLength(Context)); }, null); GetTableLength(Context); // first gets table length then calls the Acquring function, this should only need to happen once //StartCoroutine(CheckTableLength(Context)); //SimpleAddObjectToDB(Context); //SimpleRetrieveObject(Context); //DeleteObjectFromDB(Context); StartCoroutine(GetLocationWait()); //AddObjectToDB(Context); }
public static void init() { // CognitoAWSCredentials is recommended in the place of Developer credentials{accessKey,secretKey} for reasons of security best practices // CognitoAWSCredentials uses the CognitoIdentityProvider & provides temporary scoped AWS credentials from AssumeRoleWithWebIdentity // ref: http://mobile.awsblog.com/post/TxR1UCU80YEJJZ/Using-the-Amazon-Cognito-Credentials-Provider #if DEVELOPER_AUTHENTICATED_IDENTITIES // or to use developer authenticated identities CachingCognitoAWSCredentials _credentials = new CachingCognitoAWSCredentials(AmazonInitializer.DefaultUnAuthRole, AmazonInitializer.DefaultAuthRole, new ExampleIdentityProvider(), new AmazonSecurityTokenServiceClient(AmazonInitializer.CognitoRegionEndpoint)); #else // Ref: http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#create-an-identity-pool // for setting up Cognito Identity Pools, can you use the sample code for .NET SDK _credentials = new CachingCognitoAWSCredentials(); #endif // DefaultCognitoSyncManager is a high level CognitoSync Client which handles all Sync operations at a Dataset level. // Additionally, it also provides local storage of the Datasets which can be later Synchronized with the cloud(CognitoSync service) // This feature allows the user to continue working w/o internet access and sync with CognitoSync whenever possible _syncManager = new DefaultCognitoSyncManager(_credentials, new AmazonCognitoSyncConfig { RegionEndpoint = AmazonInitializer.CognitoRegionEndpoint }); }
// Start is called before the first frame update void Start() { Debug.Log("Login Client Started"); AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; awsCredentials = new CognitoAWSCredentials( "ap-south-1:0edf52b9-63a5-4fbe-9299-aa9c9413aa2d", // Identity pool ID RegionEndpoint.APSouth1 // Region ); syncManager = new CognitoSyncManager(awsCredentials, RegionEndpoint.APSouth1); dbClient = new AmazonDynamoDBClient(awsCredentials, RegionEndpoint.APSouth1); dbContext = new DynamoDBContext(dbClient); playerInfo = syncManager.OpenOrCreateDataset("playerInfo"); playerInfo.OnSyncSuccess += SyncSuccessCallBack; playerInfo.OnSyncFailure += HandleSyncFailure; fbandcsInitiated = fbandcsInitiated + 1; PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestEmail().RequestIdToken().RequestServerAuthCode(false).Build(); PlayGamesPlatform.InitializeInstance(config); PlayGamesPlatform.DebugLogEnabled = true; PlayGamesPlatform.Activate(); //Social.localUser.Authenticate(GoogleLoginCallback); }
public void onLoadPress(InputField inputField) { Amazon.AWSConfigs.HttpClient = Amazon.AWSConfigs.HttpClientOption.UnityWebRequest; var credentials = new CognitoAWSCredentials("us-west-2:f68b1fc5-4a03-4dfe-9f2d-4ce68308dd9a", RegionEndpoint.USWest2); Debug.Log(RegionEndpoint.USWest2); AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USWest2); DynamoDBContext Context = new DynamoDBContext(client); Context.LoadAsync <Album>("0", inputField.text, (AmazonDynamoDBResult <Album> result) => { if (result.Exception != null) { Debug.LogException(result.Exception); return; } images = result.Result.images; index = 0; totalImages = images.Count; StartCoroutine(changePic(images[index])); }, null); }
// Use this for initialization void Start() { UnityInitializer.AttachToGameObject(this.gameObject); AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; AWSConfigs.RegionEndpoint = RegionEndpoint.APNortheast1; //AWSConfigs.HttpClient. _credentials = new CognitoAWSCredentials("ap-northeast-1:9ef21a6c-f1dd-4458-b771-7228a364e7ab", RegionEndpoint.APNortheast1); analyticsManager = MobileAnalyticsManager.GetOrCreateInstance("d1c5b82b0d93431289415c98693ab617", _credentials, RegionEndpoint.USEast1); CustomEvent customEvent = new CustomEvent("level_complete"); customEvent.AddAttribute("LevelName", "Level1"); customEvent.AddAttribute("CharacterClass", "Warrior"); customEvent.AddAttribute("Successful", "True"); customEvent.AddMetric("Score", 12345); customEvent.AddMetric("TimeInLevel", 64); analyticsManager.RecordEvent(customEvent); }
private void InitializeDependencies() { _settings = new Settings(); #if DEBUG _settings = GetDevelopmentEnvironmentSettings(); #else _settings = GetProductionEnvironmentSettings(); #endif var credentials = new CognitoAWSCredentials( _settings.Aws.IdentityPoolId, RegionEndpoint.GetBySystemName(_settings.Aws.RegionConfig.SystemName) ); AmazonDynamoDBConfig config = new AmazonDynamoDBConfig { RegionEndpoint = RegionEndpoint.EUWest1, }; AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, config); _wishListWhiskeyUseCase = new WishListWhiskeyUseCase(new WhiskeyDataStore(client)); }
private void Start() { UnityInitializer.AttachToGameObject(this.gameObject); //AwsPrefab~のエラー対策 AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; //Cannot override~のエラー対策 // Amazon Cognito 認証情報プロバイダーを初期化、 //Invalid identity pool~のエラー対策のため情報多め credentials = new CognitoAWSCredentials( AWS_ACCOUNT, //追加 IDENTITY_POOL_ID, UNAUTH_ARN, //追加 AUTH_ARN, //追加 COGNITO_REGION ); //ダウンロードコルーチンの実行 StartCoroutine(GetTextFromS3Coroutine("test.txt", true, (a, b) => { if (a) { TekisutoHonbun.GetComponent <Text>().text = b; Debug.Log(b); } })); }