how handle refresh token service in AWS amplify-js












0














In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it's not working for me.










share|improve this question





























    0














    In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it's not working for me.










    share|improve this question



























      0












      0








      0







      In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it's not working for me.










      share|improve this question















      In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it's not working for me.







      amazon-web-services amazon-cognito aws-amplify






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 7:03

























      asked Nov 19 '18 at 13:08









      techie18

      497




      497
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).



          If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.






          share|improve this answer





















          • thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
            – techie18
            Nov 20 '18 at 13:48










          • No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
            – thomasmichaelwallace
            Nov 20 '18 at 14:36



















          0














          After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js



          const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
          const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

          componentWillReceiveProps(nextProps) {
          let getIdToken = localStorage.getItem('idToken');
          if(getIdToken !== null){
          let newDateTime = new Date().getTime()/1000;
          const newTime = Math.trunc(newDateTime);
          const splitToken = getIdToken.split(".");
          const decodeToken = atob(splitToken[1]);
          const tokenObj = JSON.parse(decodeToken);
          const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
          //console.log(newTimeMin, tokenObj.exp)
          if(newTimeMin > tokenObj.exp){
          this.tokenRefresh();
          console.log('token updated');
          }
          }
          }


          Updating the token method



          tokenRefresh(){
          const poolData = {
          UserPoolId : // Your user pool id here,
          ClientId : // Your client id here
          };
          const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
          const cognitoUser = userPool.getCurrentUser();
          cognitoUser.getSession((err, session) =>{
          const refresh_token = session.getRefreshToken();
          cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
          if (refErr) {
          throw refErr;
          }
          else{
          //this provide new accessToken, IdToken, refreshToken
          // you can add you code here once you get new accessToken, IdToken, refreshToken
          }
          });
          })
          }





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375350%2fhow-handle-refresh-token-service-in-aws-amplify-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).



            If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.






            share|improve this answer





















            • thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
              – techie18
              Nov 20 '18 at 13:48










            • No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
              – thomasmichaelwallace
              Nov 20 '18 at 14:36
















            0














            Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).



            If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.






            share|improve this answer





















            • thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
              – techie18
              Nov 20 '18 at 13:48










            • No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
              – thomasmichaelwallace
              Nov 20 '18 at 14:36














            0












            0








            0






            Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).



            If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.






            share|improve this answer












            Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).



            If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '18 at 12:54









            thomasmichaelwallace

            2,5251817




            2,5251817












            • thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
              – techie18
              Nov 20 '18 at 13:48










            • No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
              – thomasmichaelwallace
              Nov 20 '18 at 14:36


















            • thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
              – techie18
              Nov 20 '18 at 13:48










            • No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
              – thomasmichaelwallace
              Nov 20 '18 at 14:36
















            thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
            – techie18
            Nov 20 '18 at 13:48




            thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using amazon-cognito-identity-js but that also not working for me
            – techie18
            Nov 20 '18 at 13:48












            No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
            – thomasmichaelwallace
            Nov 20 '18 at 14:36




            No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the refresh token expiration in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in.
            – thomasmichaelwallace
            Nov 20 '18 at 14:36













            0














            After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js



            const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
            const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

            componentWillReceiveProps(nextProps) {
            let getIdToken = localStorage.getItem('idToken');
            if(getIdToken !== null){
            let newDateTime = new Date().getTime()/1000;
            const newTime = Math.trunc(newDateTime);
            const splitToken = getIdToken.split(".");
            const decodeToken = atob(splitToken[1]);
            const tokenObj = JSON.parse(decodeToken);
            const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
            //console.log(newTimeMin, tokenObj.exp)
            if(newTimeMin > tokenObj.exp){
            this.tokenRefresh();
            console.log('token updated');
            }
            }
            }


            Updating the token method



            tokenRefresh(){
            const poolData = {
            UserPoolId : // Your user pool id here,
            ClientId : // Your client id here
            };
            const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
            const cognitoUser = userPool.getCurrentUser();
            cognitoUser.getSession((err, session) =>{
            const refresh_token = session.getRefreshToken();
            cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
            if (refErr) {
            throw refErr;
            }
            else{
            //this provide new accessToken, IdToken, refreshToken
            // you can add you code here once you get new accessToken, IdToken, refreshToken
            }
            });
            })
            }





            share|improve this answer


























              0














              After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js



              const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
              const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

              componentWillReceiveProps(nextProps) {
              let getIdToken = localStorage.getItem('idToken');
              if(getIdToken !== null){
              let newDateTime = new Date().getTime()/1000;
              const newTime = Math.trunc(newDateTime);
              const splitToken = getIdToken.split(".");
              const decodeToken = atob(splitToken[1]);
              const tokenObj = JSON.parse(decodeToken);
              const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
              //console.log(newTimeMin, tokenObj.exp)
              if(newTimeMin > tokenObj.exp){
              this.tokenRefresh();
              console.log('token updated');
              }
              }
              }


              Updating the token method



              tokenRefresh(){
              const poolData = {
              UserPoolId : // Your user pool id here,
              ClientId : // Your client id here
              };
              const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
              const cognitoUser = userPool.getCurrentUser();
              cognitoUser.getSession((err, session) =>{
              const refresh_token = session.getRefreshToken();
              cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
              if (refErr) {
              throw refErr;
              }
              else{
              //this provide new accessToken, IdToken, refreshToken
              // you can add you code here once you get new accessToken, IdToken, refreshToken
              }
              });
              })
              }





              share|improve this answer
























                0












                0








                0






                After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js



                const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
                const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

                componentWillReceiveProps(nextProps) {
                let getIdToken = localStorage.getItem('idToken');
                if(getIdToken !== null){
                let newDateTime = new Date().getTime()/1000;
                const newTime = Math.trunc(newDateTime);
                const splitToken = getIdToken.split(".");
                const decodeToken = atob(splitToken[1]);
                const tokenObj = JSON.parse(decodeToken);
                const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
                //console.log(newTimeMin, tokenObj.exp)
                if(newTimeMin > tokenObj.exp){
                this.tokenRefresh();
                console.log('token updated');
                }
                }
                }


                Updating the token method



                tokenRefresh(){
                const poolData = {
                UserPoolId : // Your user pool id here,
                ClientId : // Your client id here
                };
                const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
                const cognitoUser = userPool.getCurrentUser();
                cognitoUser.getSession((err, session) =>{
                const refresh_token = session.getRefreshToken();
                cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
                if (refErr) {
                throw refErr;
                }
                else{
                //this provide new accessToken, IdToken, refreshToken
                // you can add you code here once you get new accessToken, IdToken, refreshToken
                }
                });
                })
                }





                share|improve this answer












                After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js



                const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
                const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

                componentWillReceiveProps(nextProps) {
                let getIdToken = localStorage.getItem('idToken');
                if(getIdToken !== null){
                let newDateTime = new Date().getTime()/1000;
                const newTime = Math.trunc(newDateTime);
                const splitToken = getIdToken.split(".");
                const decodeToken = atob(splitToken[1]);
                const tokenObj = JSON.parse(decodeToken);
                const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
                //console.log(newTimeMin, tokenObj.exp)
                if(newTimeMin > tokenObj.exp){
                this.tokenRefresh();
                console.log('token updated');
                }
                }
                }


                Updating the token method



                tokenRefresh(){
                const poolData = {
                UserPoolId : // Your user pool id here,
                ClientId : // Your client id here
                };
                const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
                const cognitoUser = userPool.getCurrentUser();
                cognitoUser.getSession((err, session) =>{
                const refresh_token = session.getRefreshToken();
                cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
                if (refErr) {
                throw refErr;
                }
                else{
                //this provide new accessToken, IdToken, refreshToken
                // you can add you code here once you get new accessToken, IdToken, refreshToken
                }
                });
                })
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 28 '18 at 7:11









                techie18

                497




                497






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375350%2fhow-handle-refresh-token-service-in-aws-amplify-js%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    Npm cannot find a required file even through it is in the searched directory