コード例 #1
0
        /// <summary>
        ///     Get refreshed token from Cognito using for the current user
        /// </summary>
        /// <param name="userRequest"></param>
        /// <returns>AuthFlowResponse</returns>
        public AuthFlowResponse ProcessRefreshToken(UserRequest userRequest)
        {
            AuthFlowResponse authResponse;

            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);
                CognitoUserPool userPool = new CognitoUserPool("XXX_XXX", userRequest.CognitoClientId, provider);
                CognitoUser     user     = new CognitoUser(userRequest.UserName, userRequest.CognitoClientId, userPool, provider, userRequest.ClientSecret)
                {
                    SessionTokens = new CognitoUserSession(null, null, userRequest.Payload.RefreshToken, DateTime.Now, DateTime.Now.AddDays(10))
                };

                InitiateRefreshTokenAuthRequest authRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN
                };
                authResponse = user.StartWithRefreshTokenAuthAsync(authRequest).Result;
                return(authResponse);
            }
            catch (Exception processRefreshTokenException)
            {
                LambdaLogger.Log(processRefreshTokenException.ToString());
                return(null);
            }
        }
コード例 #2
0
        public static async Task <AuthenticationResultType> RefreshTokenDaihuyen(AuthenticationResultType request)
        {
            try
            {
                var    accesstoken = new JwtSecurityToken(request.AccessToken);
                var    idtoken     = new JwtSecurityToken(request.IdToken);
                string userName    = idtoken.Claims.FirstOrDefault(m => m.Type.Equals("cognito:username"))?.Value;
                // get new token
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(_region);
                CognitoUserPool userPool = new CognitoUserPool(UserPoolId, _clientId, provider);
                CognitoUser     user     = new CognitoUser(userName, _clientId, userPool, provider, _clientSecret)
                {
                    SessionTokens = new CognitoUserSession(request.IdToken, request.AccessToken, request.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1))
                };
                InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                };

                AuthFlowResponse authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest);

                return(authResponse.AuthenticationResult);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #3
0
        /// <summary>Update myUser SessionTokens with RefreshToken</summary>
        /// <param name="_RefreshToken">The CognitoUser Session RefreshToken, used to get New IdToken and AccessToken</param>
        /// UPDATED 13/06/2020
        public async Task GetNewValidTokensAsync(string _RefreshToken)
        {
            // The  "Refresh token expiration (days)" (Cognito->UserPool->General Settings->App clients->Show Details) is the
            // amount of time since the last login that you can use the refresh token to get new tokens.
            // After that period the refresh will fail
            // Using DateTime.Now.AddHours(1) is a workaround for https://github.com/aws/aws-sdk-net-extensions-cognito/issues/24
            myUser.SessionTokens = new CognitoUserSession(myUser.SessionTokens.IdToken, myUser.SessionTokens.AccessToken, _RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));

            try
            {
                AuthFlowResponse context = await myUser.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                })
                                           .ConfigureAwait(false);

                myUser.SessionTokens.RefreshToken = _RefreshToken; // Problem is StartWithRefreshTokenAuthAsync return a Null RefreshToken so i will keep my current One.
                currentUserSession = new UserSession(myUser.SessionTokens.AccessToken, myUser.SessionTokens.IdToken, _RefreshToken);
                ServerSend.SendTokens(id, currentUserSession);
            }
            catch (NotAuthorizedException)
            {
                //https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html
                // refresh tokens will expire - user must login manually every x days (see user pool -> app clients -> details)
                Console.WriteLine("Ask to Client to Login Manually");
                //return new SignInContext(CognitoResult.RefreshNotAuthorized) { ResultMessage = ne.Message };
            }
            catch (Exception e)
            {
                NlogClass.target.WriteAsyncLogEvent(new AsyncLogEventInfo(new LogEventInfo(LogLevel.Error, "GetNewValidTokensAsync", "Client Name : " + myUser.Username + " | RefreshToken Create New Session failed | Exception : " + e), NlogClass.exceptions.Add));
            }
        }
コード例 #4
0
        public async Task <string> RefreshCredsAsync()
        {
            AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient
                                                               (new AnonymousAWSCredentials(), regionEndpoint);
            CognitoUserPool userPool = new CognitoUserPool(poolId, clientId, provider);

            CognitoUser user = new CognitoUser(userId, clientId, userPool, provider);

            user.SessionTokens = new CognitoUserSession(null, null, authResponse.AuthenticationResult.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));

            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };

            try
            {
                authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest).ConfigureAwait(false);

                accessToken  = authResponse.AuthenticationResult.AccessToken;
                refreshToken = authResponse.AuthenticationResult.RefreshToken;
                goodTill     = DateTime.UtcNow.AddSeconds(authResponse.AuthenticationResult.ExpiresIn);
                return(accessToken);
            }
            catch (Exception ex)
            {
                var x = ex.Message;
                throw;
            }
        }
コード例 #5
0
        public async Task <SignInContext> RefreshToken(string userName, string idToken, string accessToken, String refreshToken, DateTime issued, DateTime expires)
        {
            Debug.WriteLine("ApiCognito: ========== Called to refresh session =========");
            try
            {
                Debug.WriteLine($"//sending user:{userName}, refresh token:{refreshToken},{expires}");

                CognitoUser user = new CognitoUser("", Keys.AWS_UsersPool_ClientID, UserPool, awsProvider);
                user.SessionTokens = new CognitoUserSession(
                    idToken,
                    accessToken,
                    refreshToken,
                    issued,
                    expires
                    //DateTime.Now.AddHours(1)//this will add one more our to the session
                    );

                AuthFlowResponse context = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                })
                                           .ConfigureAwait(false);

                Debug.WriteLine("//connection went through");


                // TODO handle other challenges
                return(new SignInContext(CognitoResult.Ok)
                {
                    //User = user,
                    IdToken = context.AuthenticationResult?.IdToken,
                    RefreshToken = context.AuthenticationResult?.RefreshToken,
                    AccessToken = context.AuthenticationResult?.AccessToken,
                    TokenIssued = user.SessionTokens.IssuedTime,
                    Expires = user.SessionTokens.ExpirationTime
                });
            }

            /*
             * catch (NotAuthorizedException)
             * {
             *  Debug.WriteLine("//returning NotAuthorizedException");
             *
             *  return new SignInContext(CognitoResult.NotAuthorized);
             * }*/
            catch (Exception e)
            {
                Debug.WriteLine($"RefreshToken() threw an exception {e}");
            }
            Debug.WriteLine($"returning unknown");

            return(new SignInContext(CognitoResult.Unknown));
        }
コード例 #6
0
        private async Task <AuthenticationResultType> RefreshTokens(string refreshToken)
        {
            _logger.LogDebug("Refreshing login token");
            _logger.LogTrace("RefreshToken: " + refreshToken);
            var user = new CognitoUser(null, CLIENT_ID, _userPool, _provider);

            user.SessionTokens = new CognitoUserSession(null, null, refreshToken, DateTime.Now, DateTime.Now.AddDays(3));
            var context = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            }).ConfigureAwait(false);

            return(context.AuthenticationResult);
        }
コード例 #7
0
ファイル: AWS_MQTT.cs プロジェクト: Hosemans/airconcontrol
 //Not in use / incomplete testing.
 void RefreshToken()
 {
     try
     {
         COGNITO_USER.SessionTokens = new CognitoUserSession((string)null, COGNITO_USER.SessionTokens.AccessToken, COGNITO_USER.SessionTokens.RefreshToken, DateTime.Now, DateTime.Now.AddDays(3.0));
         COGNITO_USER.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest()
         {
             AuthFlowType = AuthFlowType.REFRESH_TOKEN
         }).Wait();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #8
0
        public async void RefreshToken(string username)
        {
            CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider);
            CognitoUser     user     = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider);

            InitiateRefreshTokenAuthRequest ra = new InitiateRefreshTokenAuthRequest()
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN
            };
            AuthFlowResponse authResponse = await user.StartWithRefreshTokenAuthAsync(ra);

            if (authResponse.AuthenticationResult != null)
            {
                cognitoUserSession = new CognitoUserSession(authResponse.AuthenticationResult.IdToken, authResponse.AuthenticationResult.AccessToken, authResponse.AuthenticationResult.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));
            }
        }
コード例 #9
0
        public async Task <bool> refreshCredentials()
        {
            if (Statics.credentials != null)
            {
                if (Statics.myidtoken.ValidTo < DateTime.Now)
                {
                    //var p2 = new AmazonCognitoIdentityProviderClient(Statics.credentials);

                    var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), Amazon.RegionEndpoint.EUWest2);
                    var userPool = new CognitoUserPool(Statics.poolID, Statics.clientID, provider);
                    var user     = new CognitoUser((string)Statics.myidtoken.Payload["email"], Statics.clientID, userPool, provider);
                    //                    var acpc = new AmazonCognitoIdentityProviderClient(Statics.creds.AccessKey, Statics.creds.SecretKey, Statics.creds.Token);
                    user.SessionTokens = new CognitoUserSession(Statics.id_token, Statics.access_token, Statics.refresh_token,
                                                                Statics.myidtoken.IssuedAt, DateTime.Now.AddHours(1));
                    //Statics.user.SessionTokens.ExpirationTime = DateTime.Now.AddHours(1);
                    var awr = new InitiateRefreshTokenAuthRequest
                    {
                        AuthFlowType = AuthFlowType.REFRESH_TOKEN
                    };

                    try
                    {
                        //Statics.authResponse = await Statics.user.StartWithRefreshTokenAuthAsync(awr);
                        Statics.authResponse = await user.StartWithRefreshTokenAuthAsync(awr);

                        Statics.user = user;
                        return(await getCredentials());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.ToString());
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine(ex.InnerException.Message);
                            Console.WriteLine(ex.InnerException.ToString());
                        }
                    }
                }
                else
                {
                    var newid = Statics.credentials.RefreshIdentityAsync();
                    return(true);
                }
            }
            return(false);
        }
コード例 #10
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            string idToken      = CookieReader.GetCookie(request, "idToken");
            string refreshToken = CookieReader.GetCookie(request, "refreshToken");

            if (string.IsNullOrWhiteSpace(idToken) || string.IsNullOrWhiteSpace(refreshToken))
            {
                response.StatusCode = 400;
                response.Body       = new JObject {
                    { "error", "idToken and refreshToken cookies are required" }
                }.ToString();
                return;
            }
            var provider    = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            var userPool    = new CognitoUserPool(Configuration.FINANCE_API_COGNITO_USER_POOL_ID, Configuration.FINANCE_API_COGNITO_CLIENT_ID, provider);
            var cognitoUser = new CognitoUser(user.Email, Configuration.FINANCE_API_COGNITO_CLIENT_ID, userPool, provider)
            {
                SessionTokens = new CognitoUserSession(null, null, refreshToken, DateTime.UtcNow, DateTime.UtcNow.AddHours(1))
            };
            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };
            var refreshResponse = cognitoUser.StartWithRefreshTokenAuthAsync(refreshRequest).Result;

            cognitoUser.SessionTokens = new CognitoUserSession(null, refreshResponse.AuthenticationResult.AccessToken, refreshToken, DateTime.Now, DateTime.Now.AddHours(1));
            cognitoUser.GlobalSignOutAsync().Wait();
            response.MultiValueHeaders = new Dictionary <string, IList <string> >
            {
                {
                    "Set-Cookie", new List <string>
                    {
                        "idToken=;Path=/;Secure;HttpOnly;expires=Thu, 01 Jan 1970 00:00:00 UTC",
                        "refreshToken=;Path=/;Secure;HttpOnly;expires=Thu, 01 Jan 1970 00:00:00 UTC"
                    }
                }
            };
            response.Body = Constants.JSON_EMPTY;
        }
コード例 #11
0
        private async Task <bool> RefreshTokenAsync()
        {
            if (CognitoUser == null)
            {
                return(false);
            }

            try
            {
                AuthFlowResponse context = await CognitoUser.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                }).ConfigureAwait(false);

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine($"RefreshToken() threw an exception {e}");
                return(false);
            }
        }
コード例 #12
0
ファイル: ApiCognito.cs プロジェクト: RidhwanDev/CognitoForms
        public async Task <SignInContext> RefreshToken(string userName, string idToken, string accessToken, String refreshToken, DateTime issued, DateTime expires)
        {
            try
            {
                var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);

                CognitoUserPool userPool = new CognitoUserPool(PoolId, ClientId, provider);
                CognitoUser     user     = new CognitoUser("", ClientId, userPool, provider);

                user.SessionTokens = new CognitoUserSession(idToken, accessToken, refreshToken, issued, expires);

                AuthFlowResponse context = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                })
                                           .ConfigureAwait(false);

                // TODO handle other challenges
                return(new SignInContext(CognitoResult.Ok)
                {
                    //User = user,
                    IdToken = context.AuthenticationResult?.IdToken,
                    RefreshToken = context.AuthenticationResult?.RefreshToken,
                    AccessToken = context.AuthenticationResult?.AccessToken,
                    TokenIssued = user.SessionTokens.IssuedTime,
                    Expires = user.SessionTokens.ExpirationTime,
                    SessionId = context.SessionID
                });
            }
            catch (NotAuthorizedException ne)
            {
                return(new SignInContext(CognitoResult.NotAuthorized));
            }
            catch (Exception e)
            {
                Console.WriteLine($"SignIn() threw an exception {e}");
            }
            return(new SignInContext(CognitoResult.Unknown));
        }
コード例 #13
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            string idToken      = CookieReader.GetCookie(request, "idToken");
            string refreshToken = CookieReader.GetCookie(request, "refreshToken");

            if (string.IsNullOrWhiteSpace(idToken) || string.IsNullOrWhiteSpace(refreshToken))
            {
                response.StatusCode = 400;
                response.Body       = new JObject {
                    { "error", "idToken and refreshToken cookies are required" }
                }.ToString();
                return;
            }
            var payload     = Function.Base64Decode(idToken.Split('.')[1]);
            var email       = JObject.Parse(payload)["email"].Value <string>();
            var provider    = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            var userPool    = new CognitoUserPool(Configuration.FINANCE_API_COGNITO_USER_POOL_ID, Configuration.FINANCE_API_COGNITO_CLIENT_ID, provider);
            var cognitoUser = new CognitoUser(email, Configuration.FINANCE_API_COGNITO_CLIENT_ID, userPool, provider)
            {
                SessionTokens = new CognitoUserSession(null, null, refreshToken, DateTime.UtcNow, DateTime.UtcNow.AddHours(1))
            };
            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };
            var refreshResponse = cognitoUser.StartWithRefreshTokenAuthAsync(refreshRequest).Result;
            var expirationDate  = DateTime.UtcNow.AddDays(30).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");

            response.MultiValueHeaders = new Dictionary <string, IList <string> >
            {
                { "Set-Cookie", new List <string> {
                      $"idToken={refreshResponse.AuthenticationResult.IdToken};Path=/;Secure;HttpOnly;Expires={expirationDate}"
                  } }
            };

            response.Body = new JObject().ToString();
        }
コード例 #14
0
        public async Task <SignInContext> RefreshToken(string userName, string idToken, string accessToken, String refreshToken, DateTime issued, DateTime expires)
        {
            try
            {
                CognitoUserPool userPool = new CognitoUserPool(Constants.COGNITO_USER_POOL_ID, Constants.COGNITO_CLIENT_ID, CognitoIdentityProviderClient);
                CognitoUser     user     = new CognitoUser("", Constants.COGNITO_CLIENT_ID, CognitoUserPool, CognitoIdentityProviderClient);

                user.SessionTokens = new CognitoUserSession(idToken, accessToken, refreshToken, issued, expires);

                AuthFlowResponse context = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                })
                                           .ConfigureAwait(false);

                // TODO handle other challenges
                return(new SignInContext(CognitoResult.Ok)
                {
                    //User = user,
                    IdToken = context.AuthenticationResult?.IdToken,
                    RefreshToken = context.AuthenticationResult?.RefreshToken,
                    AccessToken = context.AuthenticationResult?.AccessToken,
                    TokenIssued = user.SessionTokens.IssuedTime,
                    Expires = user.SessionTokens.ExpirationTime,
                    SessionId = context.SessionID
                });
            }
            catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException)
            {
                return(new SignInContext(CognitoResult.NotAuthorized));
            }
            catch (Exception e)
            {
                Console.WriteLine($"RefreshToken() threw an exception {e}");
            }
            return(new SignInContext(CognitoResult.Unknown));
        }
コード例 #15
0
    public async Task <bool> RefreshSession()
    {
        Debug.Log("RefreshSession");

        DateTime         issued           = DateTime.Now;
        UserSessionCache userSessionCache = new UserSessionCache();

        SaveDataManager.LoadJsonData(userSessionCache);

        if (userSessionCache != null && userSessionCache._refreshToken != null && userSessionCache._refreshToken != "")
        {
            try
            {
                CognitoUserPool userPool = new CognitoUserPool(userPoolId, AppClientID, _provider);

                // apparently the username field can be left blank for a token refresh request
                CognitoUser user = new CognitoUser("", AppClientID, userPool, _provider);

                // The "Refresh token expiration (days)" (Cognito->UserPool->General Settings->App clients->Show Details) is the
                // amount of time since the last login that you can use the refresh token to get new tokens. After that period the refresh
                // will fail Using DateTime.Now.AddHours(1) is a workaround for https://github.com/aws/aws-sdk-net-extensions-cognito/issues/24
                user.SessionTokens = new CognitoUserSession(
                    userSessionCache.getIdToken(),
                    userSessionCache.getAccessToken(),
                    userSessionCache.getRefreshToken(),
                    issued,
                    DateTime.Now.AddDays(30)); // TODO: need to investigate further.
                                               // It was my understanding that this should be set to when your refresh token expires...

                // Attempt refresh token call
                AuthFlowResponse authFlowResponse = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                })
                                                    .ConfigureAwait(false);

                // Debug.Log("User Access Token after refresh: " + token);
                Debug.Log("User refresh token successfully updated!");

                // update session cache
                UserSessionCache userSessionCacheToUpdate = new UserSessionCache(
                    authFlowResponse.AuthenticationResult.IdToken,
                    authFlowResponse.AuthenticationResult.AccessToken,
                    authFlowResponse.AuthenticationResult.RefreshToken,
                    userSessionCache.getUserId());

                SaveDataManager.SaveJsonData(userSessionCacheToUpdate);

                // update credentials with the latest access token
                _cognitoAWSCredentials = user.GetCognitoAWSCredentials(IdentityPool, Region);

                _user = user;

                return(true);
            }
            catch (NotAuthorizedException ne)
            {
                // https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html
                // refresh tokens will expire - user must login manually every x days (see user pool -> app clients -> details)
                Debug.Log("NotAuthorizedException: " + ne);
            }
            catch (WebException webEx)
            {
                // we get a web exception when we cant connect to aws - means we are offline
                Debug.Log("WebException: " + webEx);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception: " + ex);
            }
        }
        return(false);
    }