void FbLoginCallBack(ILoginResult result) { if (result.Error == null) { Debug.Log("Facebook login successfull"); fbauth = true; gauth = false; string uid = AccessToken.CurrentAccessToken.UserId; Debug.Log("uid is null"); if (playerInfo != null && !string.IsNullOrEmpty(playerInfo.Get("uid")) && !uid.Equals(playerInfo.Get("uid"))) { awsCredentials.Clear(); playerInfo.Delete(); } Debug.Log("aws credentials is null"); awsCredentials.AddLogin("graph.facebook.com", AccessToken.CurrentAccessToken.TokenString); Debug.Log("playerInfo is null"); playerInfo.SynchronizeOnConnectivity(); loading = true; } else { Debug.Log("Facebook Login unsuccessfully:" + result.Error); } }
public void OnPostSearch1() { RegionEndpoint region = Config.ConfigManager.GetRegion(); string idToken = HttpContext.GetTokenAsync("id_token").Result; string identityPoolId = "ap-southeast-2:c8b11111-ea22-3333-4444-555555555c5a"; string userPoolId = "ap-southeast-2_U634533B"; string providerName = $"cognito-idp.ap-southeast-2.amazonaws.com/{userPoolId}"; CognitoAWSCredentials cognitoCredentials = new CognitoAWSCredentials(identityPoolId, region); cognitoCredentials.AddLogin(providerName, idToken); IAmazonDynamoDB db = new AmazonDynamoDBClient(cognitoCredentials, region); string tableName = "Animals"; Table animalTbl = Table.LoadTable(db, tableName); var singleItem = animalTbl.GetItemAsync(AnimalId).Result; AnimalSet = new List <AnimalInfo>(); if (singleItem != null) { AnimalInfo info = new AnimalInfo(); info.AnimalId = singleItem.ContainsKey("AnimalId") ? (string)singleItem["AnimalId"] : String.Empty; info.Name = singleItem.ContainsKey("Name") ? (string)singleItem["Name"] : String.Empty; info.Age = singleItem.ContainsKey("Age") ? int.Parse(singleItem["Age"]) : 0; info.Breed = singleItem.ContainsKey("Breed") ? (string)singleItem["Breed"] : String.Empty; info.Image = singleItem.ContainsKey("Image") ? (string)singleItem["Image"] : String.Empty; AnimalSet.Add(info); } }
//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; } }
private void Init(string authProvider, string accessToken) { if (string.IsNullOrEmpty(IDENTITY_POOL_ID)) { throw new NotSupportedException("Identity Pool ID is not set"); } //Create a Credentials provider that uses Cognito Identity credentials = new CognitoAWSCredentials(IDENTITY_POOL_ID, ENDPOINT); myIdentity = credentials.GetIdentityId(); credentials.IdentityChangedEvent += (object sender, Amazon.CognitoIdentity.CognitoAWSCredentials.IdentityChangedArgs e) => { Debug.Log("Identity Changed (old: '" + e.OldIdentityId + "', new: '" + e.NewIdentityId + "')"); myIdentity = e.NewIdentityId; }; //If fbAccesToken is set, we can use Cognito's authenticated identities if (accessToken != null) { credentials.AddLogin(authProvider, accessToken); } loggedIn = true; UpdateIdentity(); }
private void Init(string authProvider, string accessToken) { enabled = true; if (string.IsNullOrEmpty(IDENTITY_POOL_ID)) { throw new NotSupportedException("Please setup your the identity pool id in SceneController"); } //Enable Logs AmazonLogging.Level = AmazonLogging.LoggingLevel.DEBUG; //Create a Credentials provider that uses Cognito Identity credentials = new CognitoAWSCredentials(IDENTITY_POOL_ID, ENDPOINT); //If fbAccesToken is set, we can use Cognito's authenticated identities if (accessToken != null) { credentials.AddLogin(authProvider, accessToken); } syncManager = new DefaultCognitoSyncManager(credentials, new AmazonCognitoSyncConfig { RegionEndpoint = ENDPOINT }); InitializeCharactersDataset(); }
public void AddAuthentication(string provider, string authToken) { Debug.Log("Cognito Identity: Adding login provider: " + provider + " auth: " + authToken + " to Cognito Id: " + m_credentials.GetCachedIdentityId()); m_credentials.AddLogin(provider, authToken); string guestName = m_guestIdCache.GetNameById(m_credentials.GetCachedIdentityId()); RefreshIdentity(guestName); }
private void FacebookLoginCallback(FBResult result) { GetComponent <CharacterList> ().enabled = true; if (FB.IsLoggedIn) { credentials.AddLogin("graph.facebook.com", FB.AccessToken); LoadFromDataset(); } }
public void FBHasLoggedIn(string token, string id) { string oldFacebookId = playerInfo.Get("FacebookId"); if (string.IsNullOrEmpty(oldFacebookId) || id.Equals(oldFacebookId)) { playerInfo.Put("FacebookId", id); credentials.AddLogin("graph.facebook.com", token); } else { Debug.Log("New user detected."); credentials.Clear(); playerInfo.Delete(); credentials.AddLogin("graph.facebook.com", token); Synchronize(); StartCoroutine(WaitForEndOfSync(id)); } }
public void AWSGetCredentialForIdentity(string jwtToken) { var credentials = new CognitoAWSCredentials("us-east-2:264e3c59-f348-43bc-8ee6-870927c4170d", bucketRegion); credentials.AddLogin( "cognito-idp.us-east-2.amazonaws.com/us-east-2_1kXC0Pa2p", jwtToken); // th ReadObjectDataAsync("sony-new-bucket", "start.jpg", credentials).Wait(); }
void CognitoLogin(string facebookToken) { Debug.Log(facebookToken); string cognitoPool = "us-east-1:53dd5506-b8ba-4543-b883-c74c206c1f4d"; RegionEndpoint cognitoRegion = RegionEndpoint.USEast1; CognitoAWSCredentials credentials = new CognitoAWSCredentials(cognitoPool, cognitoRegion); credentials.AddLogin("graph.facebook.com", facebookToken); credentials.GetCredentialsAsync(CognitoGetCredentialsCallback, null); }
//test Amazon Cognito Enhanced (Simplified) Flow with Authenticated role public void TestAuthorEnhancedFlow() { string poolId = TestRunner.StoredSettings.AuthCognitoPoolId; RegionEndpoint regionEndpoint = TestRunner.RegionEndpoint; string authProvider = TestRunner.StoredSettings.AuthProvider; string authToken = TestRunner.StoredSettings.AuthToken; CognitoAWSCredentials cognitoCredentials = new CognitoAWSCredentials(poolId, regionEndpoint); cognitoCredentials.AddLogin(authProvider, authToken); VerifyCredentailsProperties(cognitoCredentials, poolId); VerifyServiceAccess(cognitoCredentials); }
public static CognitoAWSCredentials GetIdentityPoolCredentials(string accesstoken) { CognitoAWSCredentials credentials = new CognitoAWSCredentials( identityPoolId, // Identity pool ID RegionEndpoint.USEast1 // Region ); credentials.AddLogin("Cognito", accesstoken); return(credentials); }
public DynamoDBRepository(AWSConfigs configs, string idToken) { IdentityPoolId = configs.IdentityPoolId; UserPoolId = configs.UserPoolId; CognitoPoolRegion = configs.UserPoolRegion; DynamoDBRegion = configs.DynamoDBRegion; Credentials = new CognitoAWSCredentials(IdentityPoolId, CognitoRegionEndpoint); Credentials.AddLogin(CognitoIdentityProviderName, idToken); Client = new AmazonDynamoDBClient(Credentials, DynamoDBRegionEndpoint); Context = new DynamoDBContext(Client); }
/// <summary> /// Creates the CognitoAWSCredentials for accessing AWS resources. Should only be called with an authenticated user. /// </summary> /// <param name="identityPoolID">The poolID of the identity pool the user belongs to</param> /// <param name="identityPoolRegion">The region of the identity pool the user belongs to</param> /// <returns>Returns the CognitoAWSCredentials for the user to be able to access AWS resources</returns> public CognitoAWSCredentials GetCognitoAWSCredentials(string identityPoolID, RegionEndpoint identityPoolRegion) { EnsureUserAuthenticated(); string poolRegion = UserPool.PoolID.Substring(0, UserPool.PoolID.IndexOf("_")); string providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + UserPool.PoolID; CognitoAWSCredentials credentials = new CognitoAWSCredentials(identityPoolID, identityPoolRegion); credentials.AddLogin(providerName, SessionTokens.IdToken); return(credentials); }
//test Amazon Cognito Authentication Basic (Classic) Flow with Authenticated role public void TestAuthorBasedFlow() { string accountId = TestRunner.StoredSettings.AccountId; string poolId = TestRunner.StoredSettings.AuthCognitoPoolId; RegionEndpoint regionEndpoint = TestRunner.RegionEndpoint; string authRole = TestRunner.StoredSettings.AuthAuthRole; string unauthRole = TestRunner.StoredSettings.AuthUnAuthRole; string authProvider = TestRunner.StoredSettings.AuthProvider; string authToken = TestRunner.StoredSettings.AuthToken; CognitoAWSCredentials cognitoCredentials = new CognitoAWSCredentials(accountId, poolId, unauthRole, authRole, regionEndpoint); cognitoCredentials.AddLogin(authProvider, authToken); VerifyCredentailsProperties(cognitoCredentials, poolId, accountId, unauthRole, authRole); VerifyServiceAccess(cognitoCredentials); }
public S3Storage(AWSConfigs configs, string idToken = null) { IdentityPoolId = configs.IdentityPoolId; UserPoolId = configs.UserPoolId; CognitoPoolRegion = configs.UserPoolRegion; S3Region = configs.S3Region; Credentials = new CognitoAWSCredentials(IdentityPoolId, CognitoRegionEndpoint); if (!string.IsNullOrEmpty(idToken)) { Credentials.AddLogin(CognitoIdentityProviderName, idToken); } Client = new AmazonS3Client(Credentials, S3RegionEndpoint); }
//Get AWS Credentials from the Id Token. //These credentials are used to gain direct access to AWS Services public async Task <CognitoAWSCredentials> GetAuthenticatedCredentials() { CognitoAWSCredentials credentials = new CognitoAWSCredentials( ConfigData.IdentityPoolId, // Identity pool ID RegionEndpoint.EUWest1 // Region ); //The Identity Provider in this case is the User Pool your user resides in. string idName = ConfigData.IdentityProviderName; //Get a valid OpenId token. string idToken = await GetIdToken(); //Enrich the credential. credentials.AddLogin(idName, idToken); return(credentials); }
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); } }
//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 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); }
public async Task <IActionResult> AssumeRoleWithCognitoAsync() { if (!this.HttpContext.User.Identity.IsAuthenticated) { return(new OkObjectResult("you have to sign in to access AWS resources")); } try { // Initialize the Amazon Cognito credentials provider //CognitoAWSCredentials credentials = new CognitoAWSCredentials( // "us-east-2:c6e1e652-eb33-4daa-a04e-9cb0418a92cc", // Identity pool ID // RegionEndpoint.USEast2 // Region //); var credentials = new CognitoAWSCredentials( accountId: "628654266155", identityPoolId: "us-east-2:c6e1e652-eb33-4daa-a04e-9cb0418a92cc", unAuthRoleArn: null, authRoleArn: "arn:aws:iam::628654266155:role/acme_app_access_s3", region: RegionEndpoint.USEast2 ); credentials.AddLogin("dev-220949.okta.com", GetOktaTokenMiddleware.OktaToken); var creds = credentials.GetCredentials(); var s3Client = new AmazonS3Client(credentials, RegionEndpoint.USEast2); return(await this.ObjectFromBucket(s3Client)); } catch (Exception e) { Console.WriteLine(e); throw; } }
public static void Main(string[] args) { //Set up CognitoAWSCredentials CognitoAWSCredentials credentials = new CognitoAWSCredentials( accountId, // Account number identityPoolId, // Identity pool ID unAuthRoleArn, // Role for unauthenticated users null, // Role for authenticated users, not set region); using (var s3Client = new AmazonS3Client(credentials)) { s3Client.ListBuckets(); } //Use AWS as an Unautheticated User CognitoAWSCredentials credentials = new CognitoAWSCredentials( accountId, identityPoolId, unAuthRoleArn, // Role for unauthenticated users authRoleArn, // Role for authenticated users region); using (var s3Client = new AmazonS3Client(credentials)) { // Initial use will be unauthenticated s3Client.ListBuckets(); // Authenticate user through Facebook string facebookToken = GetFacebookAuthToken(); // Add Facebook login to credentials. This clears the current AWS credentials // and retrieves new AWS credentials using the authenticated role. credentials.AddLogin("graph.facebook.com", facebookAccessToken); // This call is performed with the authenticated role and credentials s3Client.ListBuckets(); } // One more example CognitoAWSCredentials credentials = GetCognitoAWSCredentials(); // Log identity changes credentials.IdentityChangedEvent += (sender, args) => { Console.WriteLine("Identity changed: [{0}] => [{1}]", args.OldIdentityId, args.NewIdentityId); }; using (var syncClient = new AmazonCognitoSyncClient(credentials)) { var result = syncClient.ListRecords(new ListRecordsRequest { DatasetName = datasetName // No need to specify these properties //IdentityId = "...", //IdentityPoolId = "..." }); } }
internal void AWSLogin(string providerName, string accessToken) { credentials.AddLogin(providerName, accessToken); }
async void Run() { var cognitoIdp = new AmazonCognitoIdentityProviderClient(); var region = ConfigurationManager.AppSettings["region"]; var userPoolId = ConfigurationManager.AppSettings["userPoolId"]; var clientId = ConfigurationManager.AppSettings["clientId"]; var identityPoolId = ConfigurationManager.AppSettings["identityPoolId"]; var username = ConfigurationManager.AppSettings["username"]; var password = ConfigurationManager.AppSettings["password"]; var apiId = ConfigurationManager.AppSettings["apiId"]; var stage = ConfigurationManager.AppSettings["stage"]; var method = ConfigurationManager.AppSettings["method"]; var path = ConfigurationManager.AppSettings["path"]; var querystring = ConfigurationManager.AppSettings["querystring"]; try { var request = new AdminInitiateAuthRequest { AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH, ClientId = clientId, UserPoolId = userPoolId, AuthParameters = { { "USERNAME", username }, { "PASSWORD", password } } }; var response = await cognitoIdp.AdminInitiateAuthAsync(request); var idToken = response.AuthenticationResult.IdToken; var credentials = new CognitoAWSCredentials(identityPoolId, RegionEndpoint.GetBySystemName(region)); var provider = String.Format("cognito-idp.{0}.amazonaws.com/{1}", region, userPoolId); credentials.AddLogin(provider, idToken); var immutableCredentials = await credentials.GetCredentialsAsync(); var endpoint = String.Format("https://{0}.execute-api.{1}.amazonaws.com/{2}/{3}", apiId, region, stage, path); if (!String.IsNullOrWhiteSpace(querystring)) { endpoint = endpoint + "?" + querystring; } var uri = new Uri(endpoint); var headers = new Dictionary <string, string> { { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 }, { "X-Amz-Security-Token", immutableCredentials.Token }, { "content-type", "application/json" } }; var signer = new AWS4SignerForAuthorizationHeader { EndpointUri = uri, HttpMethod = method, Service = "execute-api", Region = region }; var authorization = signer.ComputeSignature( headers, querystring, AWS4SignerBase.EMPTY_BODY_SHA256, immutableCredentials.AccessKey, immutableCredentials.SecretKey); headers.Add("Authorization", authorization); HttpHelpers.InvokeHttpRequest(uri, method, headers, null); } catch (Exception ex) { Console.WriteLine("Error occurred."); Console.WriteLine(ex); } }
/// <summary> /// Login to Cognito with the Facebook token /// </summary> /// <param name="facebookToken">Facebook token.</param> private void CognitoLogin() { Log("FB Cognito auth"); credentials.AddLogin("graph.facebook.com", AccessToken.CurrentAccessToken.TokenString); credentials.GetCredentialsAsync(CognitoGetCredentialsCallback, null); }